Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Math.Pow(x, 2) not optimized to x * x neither compiler nor JIT?

I've encountered non-optimal code in several open source projects, when programmers do not think about what they are using.

There is up to a 10 times performance difference between two cases, because of Math.Pow use Exp and Ln functions in internal, how it is explained in this answer.

The usual multiplication is better than powering in most cases (with small powers), but the best, of course, is the Exponentation by squaring algorithm.

Thus, I think that the compiler or JITter must perform such optimization with powers and other functions. Why is it still not introduced? Am I right?

like image 824
Ivan Kochurkin Avatar asked Sep 22 '12 10:09

Ivan Kochurkin


1 Answers

Read the anwser you've referenced again, it clearly states that CRT uses a pow() function which Microsoft bought from Intel. The example you see using Math.Log and Math.Exp is an example the writer of the article has found in a programming book.

The "problem" with general exponentiation methods is that that they are build to produce the most accurate results for all cases. This often results in sub-optimal performance for certain cases. To increase the preformance of these certain cases, conditional logic must be added which results in performance loss for all cases. Because squaring or cubing a value is that simple to write without the Math.Pow method, there is no need to optimize these cases and taking the extra loss for all other cases.

like image 55
zeebonk Avatar answered Oct 19 '22 21:10

zeebonk