Tune String's hashCode() + equals()
Ulf Zibis
Ulf.Zibis at gmx.de
Thu Mar 4 23:28:44 UTC 2010
Am 04.03.2010 23:38, schrieb Marek Kozieł:
> 2010/3/4 Ulf Zibis<Ulf.Zibis at gmx.de>:
>
>
>>> 5.
>>> Intern string do not need hash codes co comparing cos they have same
>>> address, so first loop would return true if they are equal, after this
>>> we need only to check if they are not equal:
>>>
>>>
>>>> if (isIntern()&& anotherString.isIntern()) return false;
>>>>
>>>>
>> You are right, but
>> if (h1 != 0&& h2 != 0&& h1 != h2) return false;
>> would perform same (if already computed internal hash would be
>> back-propagated to the Java object).
>>
>>
> Could you explain what do you mean ?
>
h1 = this.hash;
h2 = otherString.hash;
See:
In hotspot/src/share/vm/prims/jvm.cpp :
JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
JVMWrapper("JVM_InternString");
JvmtiVMObjectAllocEventCollector oam;
if (str == NULL) return NULL;
oop string = JNIHandles::resolve_non_null(str);
oop result = StringTable::intern(string, CHECK_NULL);
return (jstring) JNIHandles::make_local(env, result);
JVM_END
In hotspot/src/share/vm/classfile/symbolTable.cpp :
oop StringTable::intern(Handle string_or_null, jchar* name,
int len, TRAPS) {
unsigned int hashValue = hash_string(name, len);
int index = the_table()->hash_to_index(hashValue);
oop string = the_table()->lookup(index, name, len, hashValue);
// Found
if (string != NULL) return string;
// Otherwise, add to symbol to table
return the_table()->basic_add(index, string_or_null, name, len,
hashValue, CHECK_NULL);
}
int StringTable::hash_string(jchar* s, int len) {
unsigned h = 0;
for (len = s + len*sizeof(jchar); s < len; s++)
h = 31*h + (unsigned) *s;
return h;
}
More information about the core-libs-dev
mailing list