This project is read-only.
1
Vote

VB ^ operator optimization

description

In VB 2013 it looks like "a ^ 2" just gets turned into a call to Math.Pow(a, 2.0).
It would be nice if VB could notice when an integer exponent is used, and then call a more optimized version of Pow. Something like...
' Like Math.Pow, but faster for integer exponents
Function Pow(a As Double, exp As Integer) As Double
    Dim ret = a
    For i = 2 To exp
        ret *= a
    Next
    Return ret
End Function
When profiling our application recently I found that calls to Math.Pow were a major bottleneck due to many millions of calls to square or cube numbers (a common operation in engineering calculations). We were able to improve performance by 16x by simply replacing calls to Math.Pow with the above function.

comments

AdamSpeight2008 wrote Dec 1, 2014 at 5:45 PM

You could write a code diagnostic and code-fix

MgSam wrote Dec 2, 2014 at 3:34 PM

This seems like a library problem first and foremost. The language could theoretically include optimizations, but the biggest bang for the buck would be if Math had an integer overload for Pow.

By the way, for raising integers to powers of 2 bit shifting will give you even better performance.

PauloMorgado wrote Dec 2, 2014 at 4:26 PM

Exactly! Only if the base is scalar values - Integer, Long and the likes.

For what is worth, you can use bit shifting for any integer exponent because any integer can be decomposed in powers of 2.