Question

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!

Was it helpful?

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

OTHER TIPS

Start by striving for code clarity.

Then measure performance. If there is a performance problem, identify the bottlenecks.

Any bottlenecks are highly unlikely to be in the assignment of constants (compiled or interpreted code).

Compilers will usually optimize constants like that, so even if you write (3.1416 / 3) + 1.5708 the value that will end up in your object code is 2.6179. Interpreters might do the same, but since they do it at runtime, then yes, the performance will be lower.

However, the difference will probably be negligible so, as Mitch Wheat said, you should favor code clarity. Theoretical analysis is one thing, but the only way to be sure of what are the actual bottlenecks of your particular code (in your particular environment) is testing, profiling, measuring.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top