Any way to improve JavaScript array performance?

I am porting some of my OpenGL code to WebGL, and the fact that JavaScript does not have genuine arrays is sad. I can use Float32Array (and other other types of ArrayBuffer ), but this does not seem to help performance.

As an experiment comparing the performance of Array vs Float32Array vs Float64Array , I assigned a sort of bubbles to 100,000 floats to see if there is a difference:

 function bubbleSort(array) { var N = array.length; for (var i = 0; i < N; i++) for (var j = i; j < N-1; j++) if (array[j] > array[j+1]) { var tmp = array[j]; array[j] = array[j+1]; array[j+1] = tmp; } } // var nums = new Array(100000); // regular 'JS' array // var nums = new Float32Array(100000); // actual buffer of 32-bit floats var nums = new Float64Array(100000); // actual buffer of 64-bit floats for (var i = 0; i < nums.length; i++) nums[i] = Math.random() * 1000; bubbleSort(nums); for (var i = 0; i < nums.length; i++) console.log(nums[i]); 

Not a big difference. In fact, the compiler would need static type information for the Array argument for bubbleSort in order to really get decent performance. Are we just stuck with poor array performance in JS? How to get around this? Except using ASM.js, which ...

+5
source share
1 answer

You should see this answer: What is the performance of objects / arrays in JavaScript? (special for Google V8)

In particular, the following points:

  • Array.push (data); faster than Array [nextIndex] = data is almost 20 times.
  • Writing V8 strings is slightly faster than reading V8

So yes, it looks like indexing an array in JS is slower. If it is true that the array writes faster than it reads in the performance test, then most likely the dynamic allocation is not legible, where does it put the data (fastest?), Whereas when it comes to reading, it will be a lot of memory addresses for switching between them and so will be much slower.

I would be interested to know if you declare an array using the literal syntax [0, 1, 2, ..., 100000], will the performance be better?

(I installed JSPerf if I have time).

+3
source

Source: https://habr.com/ru/post/1204031/


All Articles