VB.net比C ++快?

编程入门 行业动态 更新时间:2024-10-28 04:21:44
本文介绍了VB比C ++快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复:

$

我碰到一个有趣的问题,其中我有VB中的代码和C ++中完全相同的代码。我希望C ++自然比VB跑得快一点,但是我得到的正好相反:VB的运行速度是C ++的两倍多。程序遍历从1到2,000,000的所有数字,确定它们是否为素数,并将所有素数加在一起。以下是以下片段:

C++

C ++

C++ output:

C ++输出:

And here's the exact same thing, only written in VB

这里是完全一样的东西,只写在VB

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比C ++快。任何想法?

I feel like there's something obvious that I'm missing, because I really can't see VB 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 ++快?

本文发布于:2023-10-18 11:41:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:VB   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!