我用 Golang 和 Java 测试了几个简单的函数。令我惊讶的是,Java 有时比 Golang 更快(尤其是在递归函数和标准库中的某些函数,如 math/rand.Rand)。我想知道为什么。这是我用于测试的一些代码和结果。
Java代码:
public class Performance {
public static double calPi(int pointCount) {
int inCircleCount = 0;
double x, y;
double Pi;
for (int i = 0; i < pointCount; i++) {
x = Math.random();
y = Math.random();
if (x * x + y * y < 1) {
inCircleCount++;
}
}
Pi = (4.0 * inCircleCount) / pointCount;
return Pi;
}
public static double cal(double a, double b, double c) {
return a * b / (c + 1) + a;
}
public static long fibonacci(long c) {
if (c < 2)
return c;
return fibonacci(c - 2) + fibonacci(c - 1);
}
public static void main(String[] args) {
System.out.println("Test 1");
long startTime = System.currentTimeMillis();
double result = 0.0;
for (double i = 0.0; i < 1000000000; i = i + 1) {
result += i * i;
}
long endTime = System.currentTimeMillis();
float duration = (float) (endTime - startTime) / 1000;
System.out.println("Result: " + result);
System.out.println("Duration: " + duration + " s");
System.out.println("Test 2");
startTime = System.currentTimeMillis();
long resultInt = fibonacci(50);
endTime = System.currentTimeMillis();
duration = (float) (endTime - startTime) / 1000;
System.out.println("Result: " + resultInt);
System.out.println("Duration: " + duration + " s");
System.out.println("Test 3");
startTime = System.currentTimeMillis();
result = 0.0;
for (double i = 0; i < 100000000; i = i + 1) {
result += Math.random();
}
endTime = System.currentTimeMillis();
duration = (float) (endTime - startTime) / 1000;
}
}
Test 2结果的差异真的让我震惊!请帮我找出原因,谢谢。如果有人可以给我示例来展示 Golang(与 Java)的优势,那就更好了。
哔哔one
相关分类