首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么C#执行Math.Sqrt()比VB.NET慢?

为什么C#执行Math.Sqrt()比VB.NET慢?
EN

Stack Overflow用户
提问于 2010-06-12 04:22:06
回答 6查看 4K关注 0票数 51

背景

今天早上,在运行基准测试时,我和我的同事发现了一些关于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秒内找到相同数量的素数。

计算机规格和说明

  • 英特尔酷睿2四核6600 @2.4 6600

在我测试过的每一台机器上,C#和VB.NET之间的基准测试结果都有明显的差异。

这两个控制台应用程序都是在发布模式下编译的,但在其他情况下,项目设置不会从Visual Studio 2008生成的默认值进行更改。

VB.NET代码

代码语言:javascript
复制
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#代码

代码语言:javascript
复制
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慢?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3025968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档