2010-06-24 49 views
0

假設選項Strict On; ab - 整數CSng()或x 1F?

Dim mySingle as Single = a/b ' implicit conversion error 

A)

Dim mySingle as Single = CSng(a/b) ' CSng 

溶液B)

Dim mySingle as Single = a * 1F/b ' x 1F 

什麼溶液優選是?
如果性能很重要,需要採取什麼解決方案?

+0

解決方案A可以把你扔出如果你切換到C#(在C#中,因爲'INT/int'返回'int') – Powerlord 2010-06-24 21:16:10

回答

3

出於可讀性和揭示意圖,我會去答:

Dim mySingle as Single = CSng(a/b) ' CSng 

使用A,你都清楚地說,我知道計算返回不同的類型,這就是我想要的。對於性能 - 我運行了一個快速的微基準測試,每次測試100萬次迭代,差異在毫秒級到亞毫秒級之間,與CSing有很小的優勢。不要擔心這種轉換的性能(當然,您需要自行測試)。

基準代碼:

Sub Main() 
    Dim mySingle As Single 
    Dim a As Integer = 10 
    Dim b As Integer = 5 

    Dim iterations As Integer = 1000000 

    Dim sw As New Stopwatch() 

    sw.Start() 
    For i As Integer = 1 To iterations 
     mySingle = CSng(a/b) ' CSng ' 
    Next 
    sw.Stop() 

    Console.WriteLine(String.Format("CSng(a/b) - {0}", sw.Elapsed)) 


    sw.Reset() 
    sw.Start() 
    For i As Integer = 1 To iterations 
     mySingle = a * 1.0F/b ' x 1F ' 
    Next 
    sw.Stop() 

    Console.WriteLine(String.Format(" a * 1.0F/b - {0}", sw.Elapsed)) 

End Sub 
+0

只爲可讀性?如果表現在第一位呢? – serhio 2010-06-24 20:33:08

+0

你從未說過性能是一個問題。也許你應該修改你的問題。 – Oded 2010-06-24 20:34:30

+0

好的,反映了這個問題。 – serhio 2010-06-24 20:38:36