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')
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.
source share