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
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;”.