I am working on a Java to WebAssembly compiler (JWebAssembly). I need to replace native code with things that can run in WebAssembly.
For java.lang.Object.hashCode() and java.lang.System.identityHashCode() I use currently the follow JavaScript code:
identityHashCode = (o) => {
var h = o[1];
while( h == 0 ){
o[1] = h = Math.round( ( Math.random() - 0.5 ) * 0xffff );
}
return h;
}
But this required for every new hashCode a round trip to the JavaScript scope which cost performance. With a browserless environment (without JavaScript) like WASI this will not work. That I search for a poor replacement.
I think a hashCode:
- does not need be really random
- the values must only be well distributed
Is this correct?
The follow Java code should be good enough.
private static int globalHash = (int)System.currentTimeMillis();
private int hashCode;
public int hashCode() {
if( hashCode == 0 ) {
hashCode = globalHash = (globalHash + 1) * 31;
}
return hashCode;
}
Is this good enough for a generic hashCode function? Would there a better implementation?