假設選項Strict On
; a
和b
- 整數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
什麼溶液優選是?
如果性能很重要,需要採取什麼解決方案?
假設選項Strict On
; a
和b
- 整數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
什麼溶液優選是?
如果性能很重要,需要採取什麼解決方案?
出於可讀性和揭示意圖,我會去答:
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
解決方案A可以把你扔出如果你切換到C#(在C#中,因爲'INT/int'返回'int') – Powerlord 2010-06-24 21:16:10