简单的程序需要3倍的C#时间

时间:2018-04-02 15:31:55

标签: java c# performance

我写了一个简单的“基准”来比较相同情况下的表现 - 在Java和C#中。在Java中,程序需要大约2,2s才能完成(多次运行),在C#中它需要7,4s(多次运行)。

使用的软件:Windows,Java(JDK 10),C#(.NET Framework 4.6.1)

不是CSharp的运行时jitting,或者为什么Java的速度更快?

Java中的程序:

Dummy[] dummies = new Dummy[100000000]; // Dummy = empty class

var timer = new Timer();
timer.start();

for (int i = 0; i < 100000000; i++) {
    dummies[i] = new Dummy();
}

timer.stop();
System.out.println(String.format("Elapsed time: %sms", timer.millis(2)));

在C#中:

Dummy[] dummies = new Dummy[100000000]; // Dummy = empty class

var timer = new Timer();
timer.Start();

for (int i = 0; i < 100000000; i++)
{
    dummies[i] = new Dummy();
}

timer.Stop();
Console.WriteLine("Elapsed time: {0}ms", timer.Millis(2));

Java中的Timer类:

public class Timer {
    private long startTime, stopTime;

    public void start() {
        startTime = System.nanoTime();
        stopTime = startTime;
    }

    public void stop() {
        stopTime = System.nanoTime();
    }

    public double millis() {
        return stopTime / 1e6 - startTime / 1e6;
    }

    public double millis(int decimals) {
        double factor = Math.pow(10.0, decimals);
        return Math.round(millis() * factor) / factor;
    }
}

在C#中:

public class Timer
{
    private double startTime, stopTime;

    public void start()
    {
        startTime = TimeSpan.FromTicks(DateTime.Now.Ticks).TotalMilliseconds;
        stopTime = startTime;
    }

    public void stop()
    {
        stopTime = TimeSpan.FromTicks(DateTime.Now.Ticks).TotalMilliseconds;
    }

    public double Millis()
    {
        return stopTime - startTime;
    }

    public double Millis(int decimals)
    {
        return Math.Round(Millis(), decimals);
    }
}

0 个答案:

没有答案