The smartest way to initialize an array in CoffeeScript

What is the best way to initialize an array with a specific value of 0 in a coffee script. What have I done so far -

 [0..100].map -> 0 

AND

 arr = [] arr.push(0) while arr.length isnt 100 

If you personally feel that the first one will have poor performance, and the second is too verbose and will destroy the charm of programming in a coffee script.

Update 2: incase performance is not a problem, then this is also an option that I assume.

 arr = new Array(10).join(0).split('') 

Update 2: higher will work better than other options if the connection passed number

Update 3: After viewing a couple of JSPerf tests mentioned in the comments and answers, I tried to run them. I myself use node.js. Here are the weird results - Code -

  size = 10000000; key = 1 console.time('splits') arr1= Array(size + 1).join(key).split('') console.timeEnd('splits') console.time('maps') arr2 = [1..size].map -> key console.timeEnd('maps') console.time('loop') arr3 = [] arr3.push(key) while arr3.length isnt size console.timeEnd('loop') console.time('for') arr4 = (0 for n in [0...size]) console.timeEnd('for') console.time('for-no-var') arr5 = (0 for [0...size]) console.timeEnd('for-no-var') ### node- 0.10.15 splits: 162ms maps: 1639ms loop: 607ms for: 659ms ### 

Interestingly, split and join take much less time. Also, if we really care about performance, we should try to initialize an array that is really big, and not something in a hundred.

+4
source share
3 answers

There is also the form arr = (0 for [1..100]) , if you do not want any iteration variable to flow out of understanding;)

+13
source

My vote goes up to arr = (0 for x in [0...100])

This is clear, concise, CoffeeScript-ish, and compiles to intelligently clear Javascript:

 var arr, x; arr = (function() { var _i, _results; _results = []; for (x = _i = 0; _i < 100; x = ++_i) { _results.push(0); } return _results; })(); 
+5
source

Here is a comparison of the performance of each of the options mentioned in the question / comments

http://jsperf.com/array-initialization-in-coffeescript

for me on chrome 28

 arr = [] arr.push(0) while arr.length isnt 100 

is the fastest

and

 [0..100].map -> 0 

is the slowest.

Nevertheless, the slowest of them is about 100 thousand op / sec. Since initialization should be a relatively unusual operation, I think it’s safe to say that performance is less important here than readability.

Personally, I believe that the version for push and map versions is the most readable, but it should really be a decision made by you, and whoever else worked with this code.

+1
source

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


All Articles