其他
新来的同事问我,为什么都在说Go比Java快?我...
链接:www.jdon.com/52263
# 前言
本次小测试并不是试图说明Go是Java的替代,Go lang和Java本就不是实现相同类型任务的语言 :Java是企业开发语言,而Go是系统编程语言。
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));
}
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更快?
觉得不错,请给个「在看」
分享给你的朋友!
- End -