我用 Java 编写了一个程序,用 Go 编写了一个等效程序。我的 Java 程序执行时间约为 5.95 秒,而 Go 程序执行时间约为 41.675789791 秒。虽然 Go 的速度与 C 或 C++ 相当,因为它像 C 一样编译,但为什么会存在如此大的性能差异?程序如下:


围棋程序


package main



import (

    "math"

    "fmt"

    "time"

)


func main() {

    fmt.Printf("vvalue is %v", testFun(10, 16666611, 1000000000))

}


func fun(x float64) float64 {

    return math.Pow(x, 2) - x

}


func testFun(first float64, second float64, times int) float64 {

    var i = 0

    var result float64 = 0

    var dx float64

    dx = (second - first) / float64(times)

    for ; i < times; i++ {

        result += fun(first + float64(i) * dx)

    }

    return result * dx

}   

Java程序


public class Test {

public static void main(String[] args) {

    Test test = new Test();

    double re = test.testFun(10, 16666611, 1000000000);

    System.out.println(re);

}


private double testFun(double first, double second, long times) {

    int i = 0;

    double result = 0;

    double dx = (second - first) / times;

    for (; i < times; i++) {

        result += fun(first + i * dx);

    }

    return result * dx;

}


private double fun(double v) {

    return Math.pow(v, 2) - v;

}

}