0

I'm just curious. Maybe someone knows what JavaScript engines can optimize in 2013 and what they can't? Any assumptions for nearest future? I was looking for some good articles, but still there is no "bible" in the internet.

Ok, let's focus on single quesiton:

Suppose I have a function which is called every 10ms or in a tight loop:

function bottleneck () {

    var str = 'Some string',
        arr = [1,2,3,4],
        job = function () {
            // do something;
        };

    // Do something; 
    // console.log(Date.getTime());
}

I do not need to calculate the initial values for variables every time, as you see. But, if I move them to upper scope, I will loose on variable lookup. So is there a way to tell Javasript engine to do such an obvious thing - precalculate variables' initial values?

I've careated a jsperf to clear my question. I'm experimenting with different types. I'm especially interested in functions and primitives.

Dan
  • 55,715
  • 40
  • 116
  • 154

2 Answers2

1

if you need to call a function every 10ms, and it's a bottleneck, the first thought you should have is "I shouldn't call this function every 10ms". Something went wrong in the architecting you did. That said, see 1b in http://jsperf.com/variables-caching/2, which is about four times faster than your "cached" version - the main reason being that for every variable in your code, you're either moving up scope, or redeclaring. In 1b, we go up scope once, to get "initials", then set up local aliasses for its content, from local reference. Much time is saved.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
1

(Concerns V8)

Well the array data itself is not created but an unique array object needs to be created every-time. The backing array for the values 1,2,3,4 is shared by these objects.

The string is interned and it is actually fastest to copy paste same string everywhere as a literal rather than referencing some common variable. But for maintenance you don't really want to do that.

Don't create any new function inside a hot function, if your job function references any variables from the bottleneck function then first of all those variables will become context allocated and slow to access anywhere even in the outer function and it will prevent inlining of the bottleneck function as of now. Inlining is a big deal optimization you don't want to miss when otherwise possible.

Esailija
  • 138,174
  • 23
  • 272
  • 326