4 ms·
for(int i=0;i<10000; ++i){ // do nothing just compute hash again and again. hash = str.hashCode(); } https://github.com/Mayank
by Calzifer 1y ago
for(int i=0;i<10000; ++i){
// do nothing just compute hash again and again.
hash = str.hashCode();
}
https://github.com/MayankPratap/Samchika/blob/ebf45acad1963d5782f165b456ab0ce10d9a4690/src/main/java/com/client/Main.java#L21 https://github.com/MayankPratap/Samchika/blob/ebf45acad1963d...
"do nothing" is correct, "again and again" not so much. Java caches the hash code for Strings and since the JIT knows that (at least in recent version[1]) it might even remove this loop entirely.
[1] https://news.ycombinator.com/item?id=43854337 https://news.ycombinator.com/item?id=43854337
- hyperpape 1y agoEven in older versions, if the compiler can see that there are no side-effects, it is free to remove the loop and simply return the value from the first iteration. I'm actually pretty curious to see what this method does on versions that don't have the optimization to treat hashCodes as quasi-final. A quick test using Java 17 shows it's not being optimized away _completely_, but it's taking...~1 ns per iteration, which is not enough to compute a hash code. Edit: I'm being silly. It will just compute the hashcode the first time, and then repeatedly check that it's cached and return it. So the JIT doesn't have to do any _real_ work to make this skip the hash code calculation. So most likely, the effective code is: computeHashCode(); for (int i = 0; i < 10000; i++) { if (false) { // pretend this wouldn't have dead code elimination, and the boolean is actually checked computeHashCode(); } }
- rzzzt 1y agoJMH, the microbenchmark harness has an example that highlights this: https://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_11_Loops.java https://github.com/openjdk/jmh/blob/master/jmh-samples/src/m...
- Calzifer 1y agoAnd since benchmarking is hard is also has a helper to actually "waste" time. [1] The implementation [2] might give an idea that it is not always trivial to do nothing but still appear busy. Btw I found most of the jmh samples interesting. IMO a quite effective mix of example and documentation. (and I'm not sure there is even much other official documentation) [1] https://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_21_ConsumeCPU.java https://github.com/openjdk/jmh/blob/master/jmh-samples/src/m... [2] https://github.com/openjdk/jmh/blob/872b7203c294d90c17766d19fc9f71cea5885380/jmh-core/src/main/java/org/openjdk/jmh/infra/Blackhole.java#L433 https://github.com/openjdk/jmh/blob/872b7203c294d90c17766d19...
- mprataps 1y agoYou are write. This code does not recalculate. However, it was written just as a sample. Mainly user will provide his own method to process the file.