VB.net比C ++快? [英] VB.net faster than C++?
问题描述
$
我碰到一个有趣的问题,其中我有VB.net中的代码和C ++中完全相同的代码。我希望C ++自然比VB.net跑得快一点,但是我得到的正好相反:VB.net的运行速度是C ++的两倍多。程序遍历从1到2,000,000的所有数字,确定它们是否为素数,并将所有素数加在一起。以下是以下片段:
C++
C ++
C++ output:
C ++输出:
And here's the exact same thing, only written in VB.net
这里是完全一样的东西,只写在VB.net
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim watch As New Stopwatch
watch.Start()
Dim maxVal As Long = 2000000
Dim sumOfPrimes As Long = 0
For i As Integer = 2 To maxVal
If (isPrime(i) = True) Then
sumOfPrimes += i
End If
Next
watch.Stop()
Console.WriteLine(watch.ElapsedMilliseconds)
Console.WriteLine("The sum of all the prime numbers below " & maxVal & " is " & sumOfPrimes)
End Sub
Function isPrime(ByVal NumToCheck As Integer) As Boolean
For i As Integer = 2 To (Math.Sqrt(CDbl(NumToCheck)))
If (NumToCheck Mod i = 0) Then
Return False
End If
Next
Return True
End Function
VB output:
1643
The sum of all the prime numbers below 2000000 is 142913828922
我觉得有一些明显的缺点,因为我真的看不到VB.net比C ++快。任何想法?
I feel like there's something obvious that I'm missing, because I really can't see VB.net being faster than C++. Any ideas?
推荐答案
VB.Net解决方案在循环开始时计算一次平方根,而C ++和C#和Java等等)每次都通过循环计算平方根,因为它们的循环基元定义不同。
The VB.Net solution computes the square root once at the beginning of the loop, while C++ (and C and C# and Java and so on) all compute the square root every time through the loop because their looping primitives are defined differently.
这篇关于VB.net比C ++快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!