What is the most efficient way to access an array in Javascript?

I was recently asked what was the most efficient way to access an array in Javascript. At the moment, I suggested using the for loop and messing with the array, but then I realized that there is a native Array.reverse() method.

For curiosity, can someone help me learn this by showing examples or pointing in the right direction so that I can read it? Any suggestions on how to measure performance would also be awesome.

+52
performance javascript arrays
Mar 11 '11 at 18:38
source share
13 answers

Based on this setting:

 var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; var length = array.length; 

Array.reverse(); is the first or second slowest!

Tests here: http://jsperf.com/js-array-reverse-vs-while-loop/5

In all browsers, swap circuits are faster. There are two general types of swap algorithms (see Wikipedia ), each of which has two options.

The two types of subcategories are temporary swap and XOR summary.

Two options handle index calculations differently. The first variation compares the current left index and right index, and then decreases the right index of the array. The second variation compares the current left index and the length divided by half, and then recalculates the right index for each iteration.

You may or may not see huge differences between the two options. For example, in Chrome 18, the first options for temporary swap and XOR replacement are 60% slower than in the second option, but in Opera 12, both options for temporary swap and XOR exchange have similar performance.

Temporary swap:

The first variation:

 function temporarySwap(array) { var left = null; var right = null; var length = array.length; for (left = 0, right = length - 1; left < right; left += 1, right -= 1) { var temporary = array[left]; array[left] = array[right]; array[right] = temporary; } return array; } 

Second variation:

 function temporarySwapHalf(array) { var left = null; var right = null; var length = array.length; for (left = 0; left < length / 2; left += 1) { right = length - 1 - left; var temporary = array[left]; array[left] = array[right]; array[right] = temporary; } return array; } 



XOR swap:

The first variation:

 function xorSwap(array) { var i = null; var r = null; var length = array.length; for (i = 0, r = length - 1; i < r; i += 1, r -= 1) { var left = array[i]; var right = array[r]; left ^= right; right ^= left; left ^= right; array[i] = left; array[r] = right; } return array; } 

Second variation:

 function xorSwapHalf(array) { var i = null; var r = null; var length = array.length; for (i = 0; i < length / 2; i += 1) { r = length - 1 - i; var left = array[i]; var right = array[r]; left ^= right; right ^= left; left ^= right; array[i] = left; array[r] = right; } return array; } 



There is another swap method called destructuring assignment: http://wiki.ecmascript.org/doku.php?id=harmony:destructuring

Destructuring purpose:

The first variation:

 function destructuringSwap(array) { var left = null; var right = null; var length = array.length; for (left = 0, right = length - 1; left < right; left += 1, right -= 1) { [array[left], array[right]] = [array[right], array[left]]; } return array; } 

Second variation:

 function destructuringSwapHalf(array) { var left = null; var right = null; var length = array.length; for (left = 0; left < length / 2; left += 1) { right = length - 1 - left; [array[left], array[right]] = [array[right], array[left]]; } return array; } 

Currently, an algorithm using a destructuring assignment is the slowest of all. It is even slower than Array.reverse(); . However, algorithms using destructuring assignments and Array.reverse(); methods Array.reverse(); are the shortest examples and they look cleaner. I hope their performance improves in the future.




Another mention that modern browsers improve the performance of push and splice arrays.

In Firefox 10, this for loop algorithm using push and splice arrays competes with temporary swap and XOR swap algorithms.

 for (length -= 2; length > -1; length -= 1) { array.push(array[length]); array.splice(length, 1); } 

However, you should probably stick to the swap loop algorithms until many of the other browsers match or outperform your push and splice array.

+61
02 Feb 2018-12-12T00:
source share

Native methods are always faster.

So use Array.reverse where possible. Otherwise, an implementation that works in O(1) would be better;)

Otherwise, just use something like this

 var reverse = function(arr) { var result = [], ii = arr.length; for (var i = ii - 1;i !== 0;i--) { result.push(arr[i]); } return result; } 

Benchmark!

An interesting loop is faster if you use all three stages of the for construct instead of one.

for(var i = ii - 1; i !== 0;i--) faster than var i = ii - 1;for(;i-- !== 0;)

+17
Mar 11 '11 at 18:44
source share

I discovered a Firefox error about slow reverse performance in Firefox. Someone from Mozilla looked at the check mark used in the received message and says that it is quite misleading. In its own analysis, it is better to reverse arrays in general. (As it should be!)

+9
Mar 16 '13 at 19:35
source share

In a simple way, you can do this using a map.

 let list = [10, 20, 30, 60, 90] let reversedList = list.map((e, i, a)=> a[(a.length -1) -i]) // [90, 60...] 
+7
Aug 11 '16 at 17:15
source share

Sharing features are the fastest. Here, the inverse function I wrote is a bit like the exchange functions mentioned above, but it works faster.

 function reverse(array) { var first = null; var last = null; var tmp = null; var length = array.length; for (first = 0, last = length - 1; first < length / 2; first++, last--) { tmp = array[first]; array[first] = array[last]; array[last] = tmp; } } 

Here you can find benchmarking http://jsperf.com/js-array-reverse-vs-while-loop/19

+3
Jan 22 '14 at 1:01
source share

Since no one came up with it and did not complete the list of ways to access the array ...

 array.sort(function() { return 1; }) 

It is twice as fast as when approaching at the same time, but other than that, it is terribly slow.

http://jsperf.com/js-array-reverse-vs-while-loop/53

+3
Aug 28 '15 at 22:57
source share

Here's an example java http://www.leepoint.net/notes-java/data/arrays/arrays-ex-reverse.html showing how to change an array. Very easy to convert to javascript.

I would suggest using something that just takes time before the function is called and after the function is called. Which ever takes the least time / hours will be the fastest.

+2
Mar 11 '11 at 18:45
source share

If you want to copy the reverse version of the array and save the original as is:

 a = [0,1,2,3,4,5,6,7,8,9]; b = [] for(i=0;i<a.length;i++){ b.push(a.slice(a.length-i-1,a.length-i)[0]) } 

Output b:

 [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 
+1
Sep 28 '14 at 18:14
source share

Here is another example for constantly changing an array changing its elements:

 var theArray = ['a', 'b', 'c', 'd', 'e', 'f']; function reverseArrayInPlace(array) { for (var i = array.length - 1; i >= 0; i -= 1) { array.push(array[i]); } array.splice(0, array.length / 2); return array; }; reverseArrayInPlace(theArray); console.log(theArray); // -> ["f", "e", "d", "c", "b", "a"] 
+1
Jan 14 2018-01-15T00:
source share

Here are a few tricks I found. Credit goes to Codemanx for an original solution

 array.sort(function() { return 1; }) 

In Typescript, this can be simplified to a single line.

 array.sort(() => 1) 

 var numbers = [1,4,9,13,16]; console.log(numbers.sort(() => 1)); 

Since this will be the future of JavaScript, I thought I would share it.

Here is another trick if your array has only 2 elements

 array.push(array.shift()); 
+1
Jul 12 '16 at 3:16
source share

Another suggestion is similar to the above, but uses splicing instead:

 var myArray=["one","two","three","four","five","six"]; console.log(myArray); for(i=0;i<myArray.length;i++){ myArray.splice(i,0,myArray.pop(myArray[myArray.length-1])); } console.log(myArray); 
+1
May 8 '17 at 12:34
source share

This is the most efficient and cleanest way to reverse an array using a ternary operator.

 function reverse(arr) { return arr.length < 2 ? arr : [arr.pop()].concat(reverse(arr)); } console.log(reverse([4, 3, 3, 1])); 
+1
Oct 24 '17 at 18:40
source share

I found an easy way to do this with .slice (). reverse ()

 var yourArray = ["first", "second", "third", "...", "etc"] var reverseArray = yourArray.slice().reverse() console.log(reverseArray) 

You'll get

 ["etc", "...", "third", "second", "first"] 
0
Dec 03 '17 at 10:11
source share



All Articles