简单的性能测试说明为什么Go比Java快?


本次小测试并不是试图说明Go是Java的替代,Go lang和Java本就不是实现相同类型任务的语言 : Java是企业开发语言,而Go是系统编程语言。

我的系统配置是16 GB RAM,Intel(R)Core(TM)i7-8550U CPU 2.00GHz和500 GB SSD。
我只是使用Go和Java语言编写了一个阶乘程序,并为各种输入创建了一个分析表和时间表。

Go代码:

package main

import (
    "fmt"
    
"time"
    
"math/big"
)

func main(){
    
    allInputs := [5]int64{10000, 50000, 100000, 500000, 1000000}
    
    var i int = 1
    for i=0;i<len(allInputs);i++ {

        var before = GetTimeStamp()

        var factorial *big.Int = big.NewInt(1)
        var j int64 = 1
        for j=1; j<=allInputs[i]; j++ {
            factorial  = factorial.Mul(factorial,big.NewInt(j))
        }
        var after = GetTimeStamp()
        var elapsedTime = after - before
        fmt.Println(
"Elapsed Time for %s is %s",allInputs[i],elapsedTime)
    }
}

func GetTimeStamp() int64 {
    return time.Now().UnixNano() / int64(time.Millisecond)
}

输出:

Output:
Factorial   Time To calculate factorial
10000       0.03 seconds
50000       0.41 seconds
100000      2.252 seconds
500000      68.961 seconds
1000000     224.135 seconds

Java代码:

import java.math.BigInteger;
import java.util.*;

class Forloop {
    public static void main(String []args){
        int[] allInputs = new int[]{10000, 50000, 100000, 500000, 1000000}; 
        for(int i=0;i<allInputs.length;i++){
            BigInteger number = BigInteger.valueOf(allInputs[i]);
            BigInteger result = BigInteger.valueOf(1);
            long before = System.currentTimeMillis();
            for (int j=1;j<=allInputs[i];j++){
                result = result.multiply(BigInteger.valueOf(j));
            }
            long after = System.currentTimeMillis();
            System.out.println("Elapsed Time: "+(after - before));
        }

输出结果:

Output:
Factorial   Time To calculate factorial
10000       0.112 seconds
50000       1.185 seconds
100000      2.252 seconds
500000      89.500 seconds
1000000     385.868 seconds

从上面的程序中,我们可以看到Go对于各种输入数据处理所用的时间比Java要短。

为什么Go比Java更快?
Go被编译为机器代码并直接执行,这使得它比Java快得多。之所以如此,是因为Java使用VM来运行其代码,这使得它与Golang相比变慢。
Golang在内存管理方面也很出色,这在编程语言中至关重要。Golang没有引用但有指针。
在局部变量的情况下,与Java相比,Golang更好。局部变量在Java语言和其他语言中是存储在堆栈中。但是在Golang中有一个例外,它可以从函数返回指向局部变量的指针。