Optimizing javascript code to use integer arithmetic

There are some algorithms that "solve problems very well" under the assumption that "very good" means minimizing the number of floating point arithmetic operations in favor of integer arithmetic. Take, for example, the Bresenham line algorithm to determine which pixels to fill in order to draw a line on a canvas: the guy made almost the whole process feasible with just some simple integer arithmetic.

This situation is obviously good in many situations. But is it worth worrying about operations requiring a lot of floating point math in javascript? I understand that everything is pretty much a decimal as far as language specifications are concerned. I wonder if it's worth trying to keep things as whole as possible at all - do browsers make optimizations that might be worth it?

+4
source share
3 answers

Actually, this is no different. JavaScript has no concept of a whole. JS uses only double-precision floating-point numbers, which may or may not be integers.

Therefore, there is absolutely nothing that can be achieved in terms of performance by limiting itself to integers.

However, keep in mind that integers will be accurate up to 2 51 whereas non-integers can very easily suffer from loss of accuracy (example: 0.1), so you may get it because of this.

-1
source

In javascript you can use Int8, Uint8, Int16, etc., but it takes a little more effort than usual - see TypedArrays .

var A = new Uint32Array(new ArrayBuffer(4*n)); var B = new Uint32Array(new ArrayBuffer(4*n)); //assign some example values to A for(var i=0;i<n;i++) A[i] = i; //note RHS is implicitly converted to uint32 //assign some example values to B for(var i=0;i<n;i++) B[i] = 4*i+3; //again, note RHS is implicitly converted to uint32 //this is true integer arithmetic for(var i=0;i<n;i++) A[i] += B[i]; 

Recently, the asm.js project allowed you to compile C / C ++ code for a weird looking javascript that uses these TypedArrays so that you can use your existing C / C ++ code and it should work pretty quickly in the browser (especially if browser developers implement special optimizations for this type of code, which should happen soon).

On a side note *, if you program, you can do SIMD parallelism (see wikipeda), that is, if your code uses a set of SSEx instructions, your arithmetic will be much faster, and in fact using int8s will be twice as fast as using int16s etc.

* I do not think this is relevant for browsers because they are too difficult to use on the fly. Edit: Turns out Firefox is experimenting with such optimizations. Also Dart (true Dart, not Dart compiled in js) will be able to do this in Chrome.

+8
source

Once upon a time, computers lacked dedicated FPUs, and floating-point math was fully used with software emulation.

Modern computers have special FPUs that handle floating point math, as well as an integer. You do not need to worry about this unless you have a special circumstance.

+3
source

All Articles