最近在学习 Go,我是 Java 背景的忠实粉丝。我正在以不同的方式比较这些语言,并惊讶地发现在 Golang 与 Java 中,一个计数高达 200 亿的简单循环花费的时间要长得多。想知道是否有人可以提供任何见解,了解我是否在这里遗漏了什么。这就是我所做的:爪哇写了下面的代码,用普通main()方法执行,用Gradle构建一个可执行的jar,用命令从命令行执行:java -jar build/libs/my-executable.jarprivate void countToTwentyBillion() { long count = 0; long start = System.currentTimeMillis(); for (int k = 0; k < 10; k++) { System.out.println("On step " + k); for (int i = 0; i < 2_000_000_000; i++) { // Do nothing but count count++; } } long end = System.currentTimeMillis(); System.out.println("Total time took: " + (end - start) + " ms to get at count: " + count);}在 3 个单独的试验中,我得到了以下结果:// Total time took: 396 ms to get at count: 20000000000// Total time took: 393 ms to get at count: 20000000000// Total time took: 388 ms to get at count: 20000000000// 392 ms average去在 Go 中构建此文件,使用“go build”构建它并在命令行中使用 ./loop-counterpackage mainimport ( "fmt" "time")func main() { count := 0 nanos := time.Now().UnixNano() start := nanos / 1000000 for i := 0; i < 10; i++ { fmt.Printf("On step %d\n", i) for k := 0; k < 2000000000; k++ { count++ } } nanos = time.Now().UnixNano() end := nanos / 1000000 timeLength := end - start fmt.Printf("Total time took: %d ms to get at count: %d\n", timeLength, count)}经过 3 次单独的试验,我得到了以下结果:// Total time took: 5812 ms to get at count: 20000000000// Total time took: 5834 ms to get at count: 20000000000// Total time took: 5907 ms to get at count: 20000000000// 5,851 ms average我进入这个期望 Go 更快,最终感到惊讶。所有试验均在相同条件下在同一台机器上进行。谁能告诉什么给?
添加回答
举报
0/150
提交
取消