Home > Article > Web Front-end > How to create arrays in batches using javascript
JavaScript has many methods to create arrays in batches. In order to measure their performance, I used different methods to create an array with a length of 100000, and the keys and values are equal. At the same time, I defined the following function to measure the time it takes to create an array:
function t(fn) { var start = Date.now(); fn.call(this); var end = Date.now(); return (end - start) + 'ms'; }
The following are several commonly used methods of creating arrays and the time they take:
This method spends a lot of time on the map operation. After removing the map, it only takes 2ms
A { length: 100000 } pseudo array, NodeList and arguments are used here They are all pseudo-arrays (array-like objects). They are not arrays in the true sense, but objects with a "length attribute" and an "index attribute". The methods of the array cannot be used directly, and apply and call But this kind of pseudo array is acceptable. The Array.prototype.slice(arguments) we usually use is based on this principle.
Here, a pseudo array of length 100000 is passed to the Array function, an array of length 100000 is constructed, and then map is used to assign the value. Some students may ask, why not directly use Array(100000) to generate an array? This is because each value of the array generated through Array(100000) is undefined and cannot be traversed through map.
This is a new method in ES6, which can directly convert a pseudo array into an array
If Replace pseudo arrays with arrays, and the speed drops a lot.
First fill the array with Array.fill(), and then assign values one by one through map
I said I was shocked at the time and kept checking to see if I was missing a dozen 0. I am dissatisfied and want to try using push
#After comparison, I found that the original for loop direct assignment is the fastest, and the other methods are almost the same. .
But the for loop is really troublesome to write. It takes three sentences to do something that can be done in one sentence.
So, if there are no big requirements for performance (after all, there will not be an array as large as 100,000 in actual development), it is most convenient to use apply and Array.from.
The above is the detailed content of How to create arrays in batches using javascript. For more information, please follow other related articles on the PHP Chinese website!