Recently at work we were playing around with the following quiz question asked by IBM https://www.research.ibm.com/haifa/ponderthis/challenges/May2015.html
After a bit of effort a colleague and I have arrived at two solutions, one in GoLang https://gist.github.com/walesey/e2427c28a859c4f7bc920c9af2858492#file-main-go-L57 and the other in Java https://gist.github.com/boyter/42df7f203c0932e37980f7974c017ec5#file-puzzle-java-L63 with the performance critical method for both being playGames in Java and game in GoLang (both linked in above).
The Go program is almost a literal copy of the Java one, and yet its runtime is ~6 seconds whereas the Java one is about ~26 seconds (on my local machine). Similar numbers were replicated on a few other machines with the Go program being about ~5x faster.
The Go program is compiled using 1.7.5 and Java using version 1.8.0_65 both running on macOS Sierra 10.12.3 on a late 2013 retina Macbook Pro with 2.6GHz i5 CPU.
Why is it that the Go program is 5x faster then the Java one when most benchmarks indicate that Java should about the same runtime? It is just basic math in a loop so it seems that they should run about the same time. I could understand a second or so for the JVM start time, but this seems off.
Both programs use pretty much the same loop. All of the possible permutations of game results are created and iterated over for each starting amount of money. It just seems that for any number of looping operations in the main loop that Go is running rings around Java.
I understand that this is a "micro" benchmark, but I am wondering why exactly the Go code is massively outperforming the Java code. Is it just that Go for simple loops/math is more efficient and hence faster? Is it able to unroll the loop perhaps (although this seems unlikely to produce such a massive difference)?
If not how should you structure a Java program to get the most performance out of a simple loop and math operation?
EDIT - Thanks to Dolda2000 I have modified the Java version. It is now about the same speed as the GoLang version. Indeed the issue was the the games were created causing the Java version to have to simulate more games to determine if the game went long enough. With the changes it is running in about ~6 seconds now and has restored my faith in Java.
Update - Here is an expanded essay which discusses the background of this question in further detail.