optimizationinterpreted-languagecompiled-language

Performance of computing constants


How do the following two blocks of pseudo-code compare in terms of speed for both compiled languages and interpreted languages? (Ignoring number of digits)

Essentially, is there any performance loss by writing variables as a function of several constants, rather than computing beforehand? This often makes code more clear.

permanentNum = (3.1416 / 3) + 1.5708
return permanentNumber / userInputNumber

.

permanentNum = 2.6179
return permanentNumber / userInputNumber

Thanks!


Solution

  • Mitch Wheat's comment is absolutely correct; optimization is something to do after you have clear and correct code, and only when necessary.

    To answer the question, though, it obviously depends on the language. Any decent compiler for the C-like languages has a constant-folding optimization pass. On GCC, or Oracle's javac, or any widely used compiler, your two examples will generate the same code.

    Interpreted languages are likely slow enough that the cost of a few extra arithmetic operations is not your bottleneck, whether it does constant-folding at parse time or not. :-)