Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the JIT compiler optimize (inline) unnecessary variable declarations?

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. :-)

like image 415
JRS Avatar asked Oct 20 '11 20:10

JRS


1 Answers

By the way, just to play devil's advocate, also I wanted to point this out:

JIT inlining of the entire function looks at the length, in bytes of MSIL, and not the complexity of the calculation. Adding local variables (and expecting the JIT to enregister them) might increase the MSIL size of the function enough to make the whole function not a candidate for inlining.

This isn't likely to make as big a difference as unnecessary use of Math.Sqrt, but it is a possibility. As Eric Lippert said, you'll know more by actually measuring. However, such a measurement is only valid for one particular run of the program, and does not generalize to different processors or future versions of the .NET runtime (including service packs) that often tweak JIT behavior. So you want a combined analytical and empirical approach to optimization.

like image 164
Ben Voigt Avatar answered Oct 05 '22 09:10

Ben Voigt