tags:

views:

22

answers:

1

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?

+2  A: 

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
Oded
only for readability? What if performance is in first place?
serhio
You never stated performance being an issue. Perhaps you should revise your question.
Oded
ok, reflected this in question.
serhio
surely this could be other solution like CSng(a) / b etc :)
serhio