preface

Recently, the company asked me this rookie barbecue brother out of the spring trick, the first time out of the heart excited and nervous, afraid of the question others can not answer.

Perhaps this is the confidence of the novice!

Listen to the question, my friend

How can I quickly create an array of length n and value 1?

This problem zha see what also is not, again see also in that way, zha see: have trap!

Extraction keywords: fast, length is n value is 1.

Let’s take a look at the various possible answers.

Alternative answers

The answer to 1

    var a = [];
    for (var i = 0; i < n; i++) {
        a[i] = 1;
    }
Copy the code

Everybody knows the answer, the for loop creates an array.

Answer 2

 for (var a = [], j= 0; j< n; a[j++] = 1);
Copy the code

The answer is an upgrade of answer 1, combining assignment statements with loop increment.

Answer 3

[...new Array(n).keys()].map(() => 1);
Copy the code

. The extension operator can be used to convert an array to a comma-separated sequence of arguments, and for an object to fetch all the traversable properties of the argument object. The keys() method is used to create an iterable from an array that contains the array keys(that is, an object with the Iterator interface from ES6).

Break down the above behaviors:

The extension operator extends the attributes of an iterable into a comma-separated sequence of arguments.

From this we can see that an iterable has both object and array properties.

Answer 4

[...Array(n)].map(() => 1);
Copy the code

This answer is an evolved version of answer 3 and initializes the array directly by extending the extension operator. We found that:

Array initialization produces an empty array of length N, but the extension operator can convert it. This is the power of syntactic sugar in space ES6.

The answer may

Array(n).fill(1);
Copy the code

Some people don’t like using the map method, so ES6 gives you a fill method that fills the array with fixed values once in place.

Answer 6

Array.from({ length: n }, () => 1);
Copy the code

The array.from () method creates a new, shallow-copy Array instance from an array-like or iterable.

An array is actually an object, so objects and arrays are close relatives. What kind of array?

  • Members can be accessed by index and have the Length attribute
  • There are no methods in arrays such as push, forEach, etc

Answer 7

Array.apply(null, Array(n)).map(() => 1);
Copy the code

Using the apply method’s feature, you can clone an array by passing the initialization array as a second argument. Obviously, this is too bad for answer 4 to be recommended.

Answer 8

 let arr = new Array(n),i = arr.length;
 while (i--) {
     arr[i] = 1;
 }
Copy the code

Instead of using a for loop to initialize the array, we assign the array through a while. The result is an array of targets.

The answer to the n

Maybe you have many different answers!

Which answer is the most correct

Let’s compare these answers in terms of performance and readability.

In order to make our comparison more efficient, we need to rule out answer 2 and answer 7 first, which are not good answers!

The performance comparison

The first thing that comes to mind when you compare the performance of your code is running time. But BBQ’s measurements are professional! It is not a simple measure as shown in the code below.

Console. time(' Performance test '); // Run the code console.timeEnd(' performance test ');Copy the code

Benchmarks grill used a professional test tool, a reliable JS benchmark. Those interested can check out the github guide.

Benchmarking is an activity that measures and evaluates software performance indicators. For JS, it can guarantee the constant running context to obtain fair test results.

The test code is as follows

const Benchmark = require('benchmark'); const suite = new Benchmark.Suite; const n = 1000000; Suite. Add ('答案1', function() {let a = []; for (var i = 0; i < n; i++) { a[i] = 1; }}). Add (3 ' 'answer, function () {[... new Array (n.) the keys ()]. The map (() = > 1); }). Add (' the answer 4 ', function () {[... Array (n)]. The map (() = > 1); }).add(' answer 5', function() {Array(n).fill(1); }). Add (' answer 6 ', function () {Array. The from ({length: n}, () = > 1); }).add(' answer 8', function() {let arr = new Array(n), I = arr.length; while (i--) { arr[i] = 1; } }) .on('cycle', function(event) { console.log(String(event.target)); }) .on('complete', function() { console.log('Fastest is ' + this.filter('fastest').map('name')); }) .run({ 'async': true });Copy the code

Result: The nodeJS version is V12.14.1

The value of n The results of
n=1000000
n=100000
n=10000

Result: The nodeJS version is V10.12.0

The value of n The results of
n=1000000
n=100000
n=10000

The Ops/ SEC in the picture is the number of times the test code is executed per second, followed by the percentage sign which is the error rate.

You can see that the performance indicators of answer 5 and Answer 8 are far ahead of the other answers!

Code readability

Judging the readability of the code is completely the subjective will of BBQ brother. If there are similarities, xing even zai!

The answer to 1 Answer 3 Answer 4 The answer may Answer 6 Answer 8
readability strong weak In the In the In the weak
Sense of science and technology weak strong strong strong In the weak

so

In terms of performance and code readability, answer 5 is superior:

Array(n).fill(1);
Copy the code

However, the fill method is a new addition to an array in ES6 and is not pleasant to use in older browsers and Nodes, so you can use something else that seems to work: a while or a for loop.

Of course,

This comparison is meaningless unless you create an array:

n=100000000
Copy the code

And when you interview!

Other than that, feel free to use it!

The last

Think barbecue brother wrote a good, like attention bar; If there are any deficiencies, please do not hesitate to correct them.

Pay attention to “front-end barbecue stall” digging gold & wechat public account, get the summary and discovery of barbecue brother in the first time.