Skip to content
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

Look at ManagedString equality methods #44

Open
EvanKirshenbaum opened this issue Sep 28, 2017 · 0 comments
Open

Look at ManagedString equality methods #44

EvanKirshenbaum opened this issue Sep 28, 2017 · 0 comments

Comments

@EvanKirshenbaum
Copy link
Collaborator

[imported from HPE issue 332]

A question came up at today's meeting about using ManagedString.equals() to compare against a Java String.

Looking at the code, while ManagedString extends CharSequence, its equals() method only returns true if the object being compared against is another ManagedString.

Although ManagedString specifically extends Comparable<ManagedString>, it does have a compareTo() method that takes a CharSequence, so you can say

if (ms.compareTo(s) == 0) { ... }

This is equivalent to

if (ms.compareTo(ManagedString.valueOf(s)) == 0) { ... }

which will walk the string once (to compute a hash), create a ManagedString equivalent if one doesn’t exist, and then compare them first for equality and then character by character (on the C++ side of the JNI barrier).

The fastest way to determine equality between a ManagedString and a String is probably to use

if (ms == ManagedString.valueOf(s)) {...}

counting on the fact that ManagedStrings are reused for the same content. (Or use equals().)
But this requires walking the string once to compute the hash and looking it up in a table, so if the same string is being compared a lot, it will be far more efficient to keep a ManagedString copy of it.

But I can certainly see cases in which, especially with large strings, it's not worth it to create the ManagedString because we'll be able to get the answer (false or, with compareTo(), not equal to zero) without walking the whole string. String has a contentEquals() method that does this sort of thing, so that would probably be the best name. This could, when the argument isn't a ManagedString, do a character comparison, without interning, stopping at the first mismatch. We could also either implement compareTo(CharSequence) this way or have a second method that does this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant