I am learning Go and before this I have been using Java8. I wrote two programs to compare speed of execution between Java8 and Go.
The Java program ran in 604 seconds on and Go one took 2334.598334749 seconds. Can someone help me understand why Go program is running slow even when it is said to be faster.
➜ ~ java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
➜ ~ go version
go version go1.12.4 darwin/amd64
//Java
public class Solution {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i <= 1 * 1e8; i++) {
System.out.println(i);
}
long end = System.currentTimeMillis();
System.out.println(Duration.ofMillis(end - start).getSeconds());
}
}
//Golang
package main
import (
"fmt"
"time"
)
func main() {
var start = time.Now()
for i := 0; i<= 1 * 1e8 ;i++ {
fmt.Println(i)
}
fmt.Println(time.Now().Sub(start).Seconds())
}
First of all: your approach to benchmarking is way too naive. For the java side of things see this for example.
Meaning: your numbers are (to a large) degree meaningless.
Second: there is a misconception. Yes, go compiles to native code. But it is not "always" known for high performance, see here for example. And of course: Java performance comes out of the JIT, and as outlined by the first link, getting that to work when measuring is a bit tricky, too.
Thus the simple technical answer: your premises are flawed.
And the real point here: your example code prints to stdout. That printing is the most expensive operation here, and most of that time hasn't anything to do with the programming language, because in the end, we talk about "file io" to a system console.
So, coming back, the real point is: your "benchmark numbers" are close to meaningless.