

What my CS degree means for my day job - david_ql
http://quickleft.com/blog/dispatches-from-class-performance-tuning-your-code

======
to3m
I'm not sure Javascript is the best language for these types of experiment.
The actual code executed is too distant from the code written for the results
to be particularly meaningful. C or C++ would probably be a better bet, or,
depending on what you're looking at, assembly language. You also need to be
careful what you're measuring!

Take the second example. The array size is very small; 4 ints will fit into 1
cache line, so you only have 2 cache lines in both cases. Assuming x86, the
data cache is 4-way, so even in the worst case there should be no problems
reading from both arrays at once. The two loops version should be slower,
because you have the same memory accesses, and the same operations, but also
more bureaucratic overhead. This leads me to believe there is some other
factor at play.

Let's modify it to make the arrays larger.

Also, don't time the array setup time, and don't time the instance
instantiation time.

    
    
        var myClass = function() {
            this.array_one=[];
            this.array_two=[];
            for(var i=0;i<1000000;++i) this.array_one[i]=this.array_two[i]=i;
            this.total = 0;
        }
     
        var my_instance = new myClass();
     
        console.time('one loop');
        for (var i=0; i < 1000000; i++) my_instance.total += (my_instance.array_one[i] + my_instance.array_two[i]);
        console.timeEnd('one loop');
     
        console.time('two loops');
        for(var i=0;i<1000000;++i) my_instance.total+=my_instance.array_one[i];
        for(var i=0;i<1000000;++i) my_instance.total+=my_instance.array_two[i];
        console.timeEnd('two loops');
    

On my system at least (running firefox 19.0.2) this has the one loop case take
~950ms and the two loop case take ~1375ms. Which makes more sense.

There may be some extra overhead introduced by the regular lookup of
my_instance.total. On the other hand at 1,000,000 iterations the JIT probably
has plenty of time to figure this all out - another reason why doing this sort
of experimentation in Javascript has the potential to be confusing.

------
tang
This was really informative. Are there any other resources that explain coding
for performance gain?

