CSng() or x 1F?
Suppose option Strict On
; a
and b
- Integers
Dim mySingle as Single = a / b ' implicit conversion error
Solution A)
Dim mySingle as Single = CSng(a / b) ' CSng
Solution B)
Dim mySingle as Single = a * 1F / b ' x 1F
What开发者_开发知识库 solution is preferable?
What solution to take if performance is important?For readability and revealing intent, I would go with A:
Dim mySingle as Single = CSng(a / b) ' CSng
Using A, you are clearly saying, I know the calculation returns a different type and that's what I want.
As for performance - I ran a quick micro-benchmark testing 1 million iterations for each and the difference was in the millisecond to sub-millisecond level, with a very slight advantage to CSing
. Don't worry about performance for this kind of conversions (of course, you need to test this on your own).
Benchmark code:
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
精彩评论