I’ve read several articles and questions/answers that conclude the best practice is to let the JIT compiler do all the optimization for inline function calls. Makes sense.
What about inline variable declarations? Does the compiler optimize these as well?
That is, will this:
Dim h = (a + b + c) / 2 'Half-Perimeter
If maxEdgeLength / (Math.Sqrt(h * (h - a) * (h - b) * (h - c)) / h) <= MaximumTriangleAspectRatio Then
'Do stuff here.
End If
Have better performance than this:
Dim perimeter = a + b + c 'Perimeter
Dim h = perimeter / 2 'Half-Perimeter
Dim area = Math.Sqrt(h * (h - a) * (h - b) * (h - c)) 'Heron's forumula.
Dim inradius = area / h
Dim aspectRatio = maxEdgeLength / inradius
If aspectRatio <= MaximumTriangleAspectRatio Then
'Do stuff here.
End If
Of course I prefer the latter because it’s easier to read and debug, but I can’t afford the performance degradation if it exists.
Note: I have already identified this code as a bottleneck — No need for retorts about premature optimization. 🙂
Temporary variables having names or not is a non-issue.
But you can optimize that inequality significantly.
Your code was:
Multiply both sides by the square root, eliminating division (inequality is preserved, because square root cannot return a negative number):
Now, square both sides to eliminate that expensive square root:
Cancel, and multiply by
h.This will be a lot faster. If this calculation is repeated, consider caching the results of part of this expression for even more improvement.
Use comments to explain the formula. Getting rid of a
Math.Sqrtcall in a bottleneck function is worth writing the expression in a less-than-simple format.