Skip to content

8302871: Speed up StringLatin1.regionMatchesCI #12632

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 21 commits into from

Conversation

eirbjo
Copy link
Contributor

@eirbjo eirbjo commented Feb 18, 2023

This PR suggests we can speed up StringLatin1.regionMatchesCI by applying 'the oldest ASCII trick in the book'.

The new static method CharacterDataLatin1.equalsIgnoreCase compares two latin1 bytes for equality ignoring case. StringLatin1.regionMatchesCI is updated to use equalsIgnoreCase

To verify the correctness of equalsIgnoreCase, a new test is added to EqualsIgnoreCase with an exhaustive verification that all 256x256 latin1 code point pairs have an equalsIgnoreCase consistent with Character.toUpperCase, Character.toLowerCase.

Performance is tested for matching and mismatching cases of code point pairs picked from the ASCII letter, ASCII number and latin1 letter ranges. Results in the first comment below.


Progress

  • Change must be properly reviewed (1 review required, with at least 1 Reviewer)
  • Change must not contain extraneous whitespace
  • Commit message must refer to an issue

Issue

Reviewers

Reviewing

Using git

Checkout this PR locally:
$ git fetch https://git.openjdk.org/jdk pull/12632/head:pull/12632
$ git checkout pull/12632

Update a local copy of the PR:
$ git checkout pull/12632
$ git pull https://git.openjdk.org/jdk pull/12632/head

Using Skara CLI tools

Checkout this PR locally:
$ git pr checkout 12632

View PR using the GUI difftool:
$ git pr show -t 12632

Using diff file

Download this PR as a diff file:
https://git.openjdk.org/jdk/pull/12632.diff

@bridgekeeper
Copy link

bridgekeeper bot commented Feb 18, 2023

👋 Welcome back eirbjo! A progress list of the required criteria for merging this PR into master will be added to the body of your pull request. There are additional pull request commands available for use with this pull request.

@openjdk
Copy link

openjdk bot commented Feb 18, 2023

@eirbjo The following labels will be automatically applied to this pull request:

  • core-libs
  • i18n

When this pull request is ready to be reviewed, an "RFR" email will be sent to the corresponding mailing lists. If you would like to change these labels, use the /label pull request command.

@openjdk openjdk bot added core-libs core-libs-dev@openjdk.org i18n i18n-dev@openjdk.org labels Feb 18, 2023
@eirbjo
Copy link
Contributor Author

eirbjo commented Feb 18, 2023

Benchmark results:

Baseline:

Benchmark                                  (codePoints)  (size)  Mode  Cnt     Score    Error  Units
RegionMatchesIC.Latin1.regionMatchesIC      ascii-match    1024  avgt   15  2216.525 ± 79.626  ns/op
RegionMatchesIC.Latin1.regionMatchesIC   ascii-mismatch    1024  avgt   15     5.049 ±  0.044  ns/op
RegionMatchesIC.Latin1.regionMatchesIC     number-match    1024  avgt   15   708.977 ± 19.381  ns/op
RegionMatchesIC.Latin1.regionMatchesIC  number-mismatch    1024  avgt   15     3.726 ±  0.036  ns/op
RegionMatchesIC.Latin1.regionMatchesIC       lat1-match    1024  avgt   15  2134.499 ± 23.064  ns/op
RegionMatchesIC.Latin1.regionMatchesIC    lat1-mismatch    1024  avgt   15     4.227 ±  0.070  ns/op

Patch:

Benchmark                                  (codePoints)  (size)  Mode  Cnt     Score    Error  Units
RegionMatchesIC.Latin1.regionMatchesIC      ascii-match    1024  avgt   15   809.729 ± 40.257  ns/op
RegionMatchesIC.Latin1.regionMatchesIC   ascii-mismatch    1024  avgt   15     4.334 ±  0.031  ns/op
RegionMatchesIC.Latin1.regionMatchesIC     number-match    1024  avgt   15   370.814 ± 39.790  ns/op
RegionMatchesIC.Latin1.regionMatchesIC  number-mismatch    1024  avgt   15     3.766 ±  0.072  ns/op
RegionMatchesIC.Latin1.regionMatchesIC       lat1-match    1024  avgt   15  1247.979 ±  7.826  ns/op
RegionMatchesIC.Latin1.regionMatchesIC    lat1-mismatch    1024  avgt   15     4.819 ±  0.026  ns/op

@eirbjo eirbjo marked this pull request as ready for review February 18, 2023 09:28
@eirbjo
Copy link
Contributor Author

eirbjo commented Feb 20, 2023

/issue 8302871

@openjdk openjdk bot changed the title Speed up StringLatin1.regionMatchesCI 8302871: Speed up StringLatin1.regionMatchesCI Feb 20, 2023
@openjdk
Copy link

openjdk bot commented Feb 20, 2023

@eirbjo The primary solved issue for a PR is set through the PR title. Since the current title does not contain an issue reference, it will now be updated.

@openjdk openjdk bot added the rfr Pull request is ready for review label Feb 20, 2023
@mlbridge
Copy link

mlbridge bot commented Feb 20, 2023

* @param b2 another byte representing a latin1 code point
* @return true if the two bytes are considered equals ignoring case in latin1
*/
static boolean equalsIgnoreCase(byte b1, byte b2) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps put this in CharacterDataLatin1, keeping it close to toLowerCase/toUpperCase that you're changing to use similar logic with #12623

If you apply #12623 first - how much difference does this make on the micro you're adding with this PR?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it not already in CharacterDataLatin1?

Here is a comparison of relying on improvements in CharacterDataLatin1.toUpperCase/toLowerCase only vs. using CharacterDataLatin1.equalsIgnoreCase:

Character.toUpperCase/toLowerCase only:

Benchmark                                  (codePoints)  (size)  Mode  Cnt     Score    Error  Units
RegionMatchesIC.Latin1.regionMatchesIC      ascii-match    1024  avgt   15  1310.582 ± 84.777  ns/op
RegionMatchesIC.Latin1.regionMatchesIC   ascii-mismatch    1024  avgt   15     4.547 ±  0.545  ns/op
RegionMatchesIC.Latin1.regionMatchesIC     number-match    1024  avgt   15   686.947 ± 11.850  ns/op
RegionMatchesIC.Latin1.regionMatchesIC  number-mismatch    1024  avgt   15     3.836 ±  0.634  ns/op
RegionMatchesIC.Latin1.regionMatchesIC       lat1-match    1024  avgt   15  2107.219 ± 17.662  ns/op
RegionMatchesIC.Latin1.regionMatchesIC    lat1-mismatch    1024  avgt   15     4.924 ±  0.829  ns/op

CharacterDataLatin1.equalsIgnoreCase:

Benchmark                                  (codePoints)  (size)  Mode  Cnt     Score    Error  Units
RegionMatchesIC.Latin1.regionMatchesIC      ascii-match    1024  avgt   15   742.467 ± 34.490  ns/op
RegionMatchesIC.Latin1.regionMatchesIC   ascii-mismatch    1024  avgt   15     3.960 ±  0.046  ns/op
RegionMatchesIC.Latin1.regionMatchesIC     number-match    1024  avgt   15   361.158 ± 37.096  ns/op
RegionMatchesIC.Latin1.regionMatchesIC  number-mismatch    1024  avgt   15     4.039 ±  0.521  ns/op
RegionMatchesIC.Latin1.regionMatchesIC       lat1-match    1024  avgt   15  1158.091 ± 41.617  ns/op
RegionMatchesIC.Latin1.regionMatchesIC    lat1-mismatch    1024  avgt   15     4.358 ±  0.123  ns/op

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, I lost context and thought this was in StringLatin1.

Thanks for running the numbers with #12623. Looks like you're getting big enough of an improvement on top.

Copy link
Contributor Author

@eirbjo eirbjo Feb 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, seems equalsIgnoreCase carries its weight.

@openjdk
Copy link

openjdk bot commented Feb 21, 2023

@eirbjo This change now passes all automated pre-integration checks.

ℹ️ This project also has non-automated pre-integration requirements. Please see the file CONTRIBUTING.md for details.

After integration, the commit message for the final commit will be:

8302871: Speed up StringLatin1.regionMatchesCI

Reviewed-by: redestad, martin, alanb

You can use pull request commands such as /summary, /contributor and /issue to adjust it as needed.

At the time when this comment was updated there had been 18 new commits pushed to the master branch:

As there are no conflicts, your changes will automatically be rebased on top of these commits when integrating. If you prefer to avoid this automatic rebasing, please check the documentation for the /integrate command for further details.

As you do not have Committer status in this project an existing Committer must agree to sponsor your change. Possible candidates are the reviewers of this PR (@cl4es, @Martin-Buchholz, @AlanBateman) but any other Committer may sponsor as well.

➡️ To flag this PR as ready for integration with the above commit message, type /integrate in a new comment. (Afterwards, your sponsor types /sponsor in a new comment to perform the integration).

@openjdk openjdk bot added the ready Pull request is ready to be integrated label Feb 21, 2023
@@ -160,6 +160,26 @@ class CharacterDataLatin1 extends CharacterData {
}
return mapChar;
}
/**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume you should insert a blank line between the two methods.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been fixed now.

return true;
}
// uppercase b1 using 'the oldest ASCII trick in the book'
int U = b1 & 0xDF;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sure some people reading this comment will wonder which book :-) It might be better to drop that bit and if possible, find a better name for "U" as normally variables start with a lower case.

Copy link
Contributor Author

@eirbjo eirbjo Feb 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Alan,

I thought I was clever by encoding the 'uppercaseness' in the variable name, but yeah I'll find a better name :)

There is some precedent for using the 'ASCII trick' comment in the JDK. I found it in ZipFile.isMetaName, which is also where I first learned about this interesting relationship between ASCII (and also latin1) letters.

The comment was first added by Martin Buchholz back in 2016 as part of JDK-8157069, 'Assorted ZipFile improvements'. In 2020, Claes was updating this code and Lance had some input about clarifying the comment. Martin then chimed in to defend his comment:

I still like my ancient "ASCII trick" comment.

I think this 'trick', whatever we call it, is sufficiently intricate that it deserves to be called out somehow and that we should not just casually bitmask with these magic constants without any discussion at all.

An earlier iteration of this PR included a small essay in the javadoc of this method describing the layout and relationship of letters in latin1 and how we can apply that knowledge of the layout to implement the method.

How would you feel about adding that description back to the Javadocs? This would then live close to the similarly implemented toUpperCase and toLowerCase methods currently under review in #12623.

Here's the updated discussion included in the Javadoc:

    /**
     * Compares two latin1 code points, ignoring case considerations.
     *
     * Implementation note: In ISO/IEC 8859-1, the uppercase and lowercase
     * letters are found in the following code point ranges:
     *
     * 0x41-0x5A: Uppercase ASCII letters: A-Z
     * 0x61-0x7A: Lowercase ASCII letters: a-z
     * 0xC0-0xD6: Uppercase latin1 letters: A-GRAVE - O with Diaeresis
     * 0xD8-0xDE: Uppercase latin1 letters: O with slash - Thorn
     * 0xE0-0xF6: Lowercase latin1 letters: a-grave - o with Diaeresis
     * 0xF8-0xFE: Lowercase latin1 letters: o with slash - thorn
     *
     * While both ASCII letter ranges are contiguous, the latin1 ranges are not:
     *
     * The 'multiplication sign' 0xD7 splits the uppercase range in two.
     * The 'division sign' 0xF7 splits the lowercase range in two.
     *
     * Lowercase letters are found 32 positions (0x20) after their corresponding uppercase letter.
     * The 'division sign' and 'multiplication sign' have the same relative distance.
     *
     * Since 0x20 is a single bit, we can apply the 'oldest ASCII trick in the book' to
     * lowercase any letter by setting the bit:
     *
     * ('C' | 0x20) == 'c'
     *
     * By removing the bit, we can perform the uppercase operation:
     *
     * ('c' & 0xDF) == 'C'
     *
     * Applying this knowledge of the latin1 layout, we can test for equality ignoring case by
     * checking that the code points are either equal, or that one of the code points is a letter
     * which uppercases is the same as the uppercase of the other code point.
     *
     * @param b1 byte representing a latin1 code point
     * @param b2 another byte representing a latin1 code point
     * @return true if the two bytes are considered equals ignoring case in latin1
     */
     static boolean equalsIgnoreCase(byte b1, byte b2) {
         if (b1 == b2) {
             return true;
         }
         int upper = b1 & 0xDF;
         if (upper < 'A') {
             return false;  // Low ASCII
         }
         return (upper <= 'Z' // In range A-Z
                 || (upper >= 0xC0 && upper <= 0XDE && upper != 0xD7)) // ..or A-grave-Thorn, excl. multiplication
                 && upper == (b2 & 0xDF); // b2 has same uppercase
    }     

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps @Martin-Buchholz could chime in and also tell us which book he found his ASCII trick in :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"oldest trick in the book" is a phrase that does not necessarily imply existence of an actual book!

Let this evoke an image of a personal book of tricks that programmers in the 1960s might have recorded such techniques in. And the tricks were passed down across generations of programmers!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More to the point, ASCII was obviously designed to allow you to uppercase a lower case letter with a single instruction, so "the book" might have been a draft standard before they scrubbed out the interesting history!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More history: IIRC I originally used 'ASCII trick' when I was truly only cared about ASCII, not Latin1 (e.g. ZipFile.isMetaName) and it's a slight misnomer to use "ASCII" here. But Latin1 followed the precedent of ASCII.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have an opinion on the appropriate level of documentation / comments for this kind of 'tricky' code?

This code is not that tricky! And the proposed level of documentation is excessive! A couple of lines of explanation and perhaps a link to an external document would be good.

It often happens to me that I will write such exhaustive notes for myself when learning a new technology. A year later I pare it all back because much of it is "obvious in retrospect".

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Martin, David, Alan. This was instructive (and fun!)

I suggest we condense the comment to something like this:

// Uppercase b1 by removing a single bit
int upper = b1 & 0xDF;
if (upper < 'A') {
    return false;  // Low ASCII
}
...

The similar methods toLowerCase toUpperCase just above have been updated to follow the same style. (I also updated local variable names there to align better with equalsIgnoreCase)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// ASCII and Latin-1 were designed to optimize case-twiddling operations

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! This expresses the higher-level benefit succinctly, without getting into the details. I like it!

public void checkConsistencyWithCharacterUppercaseLowerCase() {
for (int ab = 0; ab < 256; ab++) {
for (int bb = 0; bb < 256; bb++) {
char a = (char) ab, b = (char) bb;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

char is an unsigned numeric type, so cleaner is

for (char a = 0; a < 256; a++)
for (char b = 0; b < 256; b++)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed. Might have been copied over from processing of code points in the higher planes. Not needed here.

@eirbjo
Copy link
Contributor Author

eirbjo commented Feb 22, 2023

Thanks for reviews Claes and Martin! I'll let this linger a bit before integrating in case Alan has comments after the latest updates.

eirbjo added a commit to eirbjo/jdk that referenced this pull request Feb 22, 2023
@eirbjo
Copy link
Contributor Author

eirbjo commented Feb 23, 2023

I found this in Appendix A of the 1973 Draft Proposed Revision of ASCII. Seems compatibility with existing 6-bit devices might have been the primary concern:

A 6.4 It is expected that devices having the capability of
printing only 64 graphic symbols will continue to be important.
It may be desirable to arrange these devices to print one symbol
for the bit pattern of both upper and lower case of a given
alphabetic letter. To facilitate this, there should be a single-
bit difference between the upper and lowercase representations
of any given letter. Combined with the requirement that a given
case of the alphabet be contiguous, this dictated the assignment
of the alphabet, as shown in columns 4 through 7.

ascii

https://ia800606.us.archive.org/17/items/enf-ascii-1972-1975/Image070917152640_text.pdf

@eirbjo
Copy link
Contributor Author

eirbjo commented Feb 23, 2023

Seems compatibility with existing 6-bit devices might have been the primary concern:

This also explains the placement of brackets, braces, bars, tilde etc. They would look visually similar on 6-bit devices:

image

@eirbjo
Copy link
Contributor Author

eirbjo commented Feb 24, 2023

/integrate

@openjdk openjdk bot added the sponsor Pull request is ready to be sponsored label Feb 24, 2023
@openjdk
Copy link

openjdk bot commented Feb 24, 2023

@eirbjo
Your change (at version 597b346) is now ready to be sponsored by a Committer.

@AlanBateman
Copy link
Contributor

I'll let this linger a bit before integrating in case Alan has comments after the latest updates.

I plan to look at it, been busy with other things.

@eirbjo
Copy link
Contributor Author

eirbjo commented Feb 24, 2023

Thanks, Alan 👍 Sponsors, hold your horses! (Not sure how to 'undo' the integrate command)

@AlanBateman
Copy link
Contributor

/sponsor

@openjdk
Copy link

openjdk bot commented Feb 25, 2023

Going to push as commit 17e3769.
Since your change was applied there have been 21 commits pushed to the master branch:

  • b4ea807: 8288912: vmTestbase/nsk/stress/strace/strace002.java fails with Unexpected method name: currentCarrierThread
  • ccf3340: 8303083: (bf) Remove private DirectByteBuffer(long, int) constructor before JDK 21 GA
  • 83d77b1: 8303072: Memory leak in exeNullCallerTest.cpp
  • 7d8b8ba: 8303131: pandoc.exe mangles all processed html files
  • 8f7c496: 8302810: NMT gtests don't correctly check for marked ranges
  • 1a07871: 8302173: Button border overlaps with button icon on macOS system LaF
  • 796cdd5: 8302677: JFR: Cache label and contentType in EventType and ValueDescriptor
  • 6b24b4a: 8302821: JFR: Periodic task thread spins after recording has stopped
  • 4d33fbd: 8303089: [jittester] Add time limit to IRTree generation
  • f612dcf: 8302512: Update IANA Language Subtag Registry to Version 2023-02-14
  • ... and 11 more: https://git.openjdk.org/jdk/compare/07e976ac26fe3ff6a94713013114dc38c95950b8...master

Your commit was automatically rebased without conflicts.

@openjdk openjdk bot added the integrated Pull request has been integrated label Feb 25, 2023
@openjdk openjdk bot closed this Feb 25, 2023
@openjdk openjdk bot removed ready Pull request is ready to be integrated rfr Pull request is ready for review sponsor Pull request is ready to be sponsored labels Feb 25, 2023
@openjdk
Copy link

openjdk bot commented Feb 25, 2023

@AlanBateman @eirbjo Pushed as commit 17e3769.

💡 You may see a message that your pull request was closed with unmerged commits. This can be safely ignored.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
core-libs core-libs-dev@openjdk.org i18n i18n-dev@openjdk.org integrated Pull request has been integrated
Development

Successfully merging this pull request may close these issues.

6 participants