背景
今天早上,在运行基准测试时,我和我的同事发现了一些关于C#代码与VB.NET代码性能的奇怪事情。
我们开始比较C#和Delphi Prism计算质数,发现Prism大约快了30%。我认为CodeGear在生成IL时对代码进行了更多的优化( exe
大约是C#的两倍,并且包含各种不同的IL )。
我决定也用VB.NET编写一个测试,假设微软的编译器最终会为每种语言编写基本上相同的IL。然而,结果更令人震惊:使用相同的操作,代码在C#上的运行速度比VB慢三倍以上!
生成的IL是不同的,但不是非常不同,我在阅读它方面不够好,无法理解其中的差异。
基准测试
我已经包含了下面每一个的代码。在我的机器上,VB在大约6.36秒内找到了348513个素数。C#在21.76秒内找到相同数量的素数。
计算机规格和说明
在我测试过的每一台机器上,C#和VB.NET之间的基准测试结果都有明显的差异。
这两个控制台应用程序都是在发布模式下编译的,但在其他情况下,项目设置不会从Visual Studio 2008生成的默认值进行更改。
VB.NET代码
Imports System.Diagnostics
Module Module1
Private temp As List(Of Int32)
Private sw As Stopwatch
Private totalSeconds As Double
Sub Main()
serialCalc()
End Sub
Private Sub serialCalc()
temp = New List(Of Int32)()
sw = Stopwatch.StartNew()
For i As Int32 = 2 To 5000000
testIfPrimeSerial(i)
Next
sw.Stop()
totalSeconds = sw.Elapsed.TotalSeconds
Console.WriteLine(String.Format("{0} seconds elapsed.", totalSeconds))
Console.WriteLine(String.Format("{0} primes found.", temp.Count))
Console.ReadKey()
End Sub
Private Sub testIfPrimeSerial(ByVal suspectPrime As Int32)
For i As Int32 = 2 To Math.Sqrt(suspectPrime)
If (suspectPrime Mod i = 0) Then
Exit Sub
End If
Next
temp.Add(suspectPrime)
End Sub
End Module
C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace FindPrimesCSharp {
class Program {
List<Int32> temp = new List<Int32>();
Stopwatch sw;
double totalSeconds;
static void Main(string[] args) {
new Program().serialCalc();
}
private void serialCalc() {
temp = new List<Int32>();
sw = Stopwatch.StartNew();
for (Int32 i = 2; i <= 5000000; i++) {
testIfPrimeSerial(i);
}
sw.Stop();
totalSeconds = sw.Elapsed.TotalSeconds;
Console.WriteLine(string.Format("{0} seconds elapsed.", totalSeconds));
Console.WriteLine(string.Format("{0} primes found.", temp.Count));
Console.ReadKey();
}
private void testIfPrimeSerial(Int32 suspectPrime) {
for (Int32 i = 2; i <= Math.Sqrt(suspectPrime); i++) {
if (suspectPrime % i == 0)
return;
}
temp.Add(suspectPrime);
}
}
}
为什么C#的Math.Sqrt()
执行速度比VB.NET慢?
https://stackoverflow.com/questions/3025968
复制相似问题