Skip to content
Advertisement

Does putting intermediary math results into variables improve performance in javascript?

I have been playing around with the Riemann zeta function. I want to optimize execution time as much as possible here so I put the intermediary results in temporary variables. But testing revealed that I get no performance boost from this. At least not noticeably.

function zeta(z, limit){
    var zres = new Complex(0, 0);

        for(var x = 1; x <= limit; x++){
            var ii = z.imaginary * Math.log(1/x);
            var pp = Math.pow(1/x, z.real);
            zres.real += pp * Math.cos(ii);
            zres.imaginary += pp * Math.sin(ii);
        }

    return zres;
}

My question is: Even though I couldn’t measure a difference in execution time, what’s theoretically faster? Calculating ii and pp once and handing them over as variables, or calculating them twice and not wasting time with the declaration?

Advertisement

Answer

Putting things in (local) variables on its own will usually not have a major effect on performance. If anything it could increase the pressure on the register allocator (or equivalent) and slightly reduce performance.

Avoiding calculating expressions multiple times by putting the result into a local variable can improve performance if the just-in-time compiler (or runtime) isn’t smart enough to do the equivalent optimization (i.e. compute the value only once and re-use the computation result each times the expression is used).

There’s really no universally applicable rule here. You need to benchmark and optimize on the specific system you want best performance on.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement