JavaScript has many ways to create arrays in bulk, and in order to measure their performance, I use different methods to create an array of length 100000, with the keys and values Equal. At the same time, I defined the following function to measure the time spent creating an array:
1 function t (fn) {2 var start = Date.now (); 3 Fn.call (this); 4 var end = Date.now (); 5 return (end-start) + ' Ms '; 6 }
Here are a few common ways to create an array and the time they consume:
using join and split
This method takes a lot of time to map operations, removing the map requires only 2ms
Using apply
A pseudo-array of {length:100000} is used here, both nodelist and arguments are pseudo-arrays (array-like object), both of which are not really arrays, but with a "length property" and "indexed properties" Objects that cannot be directly used by the array, and apply and call can accept this pseudo-array. Our usual Array.prototype.slice (arguments) is based on this principle.
Here the Pseudo-array of length 100000 is passed to the array function, a 100000-length array is constructed, and then the map is assigned a Value. Some classmates might ask, why not directly array (100000) is generated because each value generated by array (100000) is undefined and cannot be traversed by map.
Using Array.from ()
This is a new method for ES6, which can convert a Pseudo-array directly to a group
If you change a pseudo-array into an array, the speed drops a lot.
Using Array.fill ()
Populate the array with Array.fill (), and then use map to assign a value
Using a For loop
I said I was stunned, and have been checking to make a 0 less. I'm not satisfied, I want to try it with push
Find push to be quick oh ...
By comparison, It is found that the most primitive for loop is directly assigned the fastest, and several other methods are similar in Speed.
But the For loop is a hassle to write, and a sentence can be done with three sentences to Fix.
therefore, If the performance is not very much required (after all, in the actual development will not have 100000 so large array), using apply and Array.from is the most convenient.
JS Batch Create array