Javascript is surprisingly fast in modern browsers, but as for every language you will need to optimize at some point. I found a very useful website called JSPerf which provides a test framework, allows you to create and edit existing test framework, provides online persistence allowing to get wider results than if you ran them by yourself.
A simple example. I was wondering what was the fastest way to convert from a float to an int in Javascript. I had several options, and the best way was not as suggested by some colleagues. And the way to make sure what is the fastest way is to benchmark, and not to guess. The results of the benchmark are here, you can test on your machine by running the test. Your results will be stored and shared with everyone, enhancing the global knowledge. The fastest I found is the following, if you find faster, please let me know.
myInt = myFloat | 0
A second example. What is the fastest typed array to write and read integers? The results are here and sadly there is no fastest answer for all browsers. So if you do not want to complicate your code with browser tests and everything that goes with it, the best solution is to use the following.
var myArray = new Int32Array( size );
A third interesting example about the fastest way to clear a buffer and copy it in a canvas every frame. The results are here. The fastest way is to create a working buffer outside your frame, create another one initialized with the values you want, and copy using the method set every frame.
At initialization time
var external_data_1024 = ctx.createImageData(1024, 1024);
var external_source_1024 = ctx.createImageData(1024, 1024);
During the frame processing
external_data_1024.data.set(external_source_1024.data);
ctx.putImageData(external_data_1024, 0, 0);
Finally a word of caution, make sure you benchmark the right things.
- The initial float to int did not include the two solutions I added to the benchmark |0 and >>0, so having something that look fast does not mean you have found the optimal solutions.
- The original array speed test included array creation for the write, so the test was measuring creation+write instead of just write, and the results were very different. So make sure to measure what really matters to you.
- The last example was a subtle example of the points #1 and #2 above. The initial “fastest” function included unnecessary code in clear_canvas(), adding a new test without that code proved to be faster. The loop test was looping with a double indirection “data.data[i] = 0;”, removing that indirection made it much faster and measured the real filling time instead of the sum of filling time+overhead with “buffer[i] = 0;”.