I've been exploring efficient methods for creating an array by repeating an element a specified number of times. In my case, the repeated element is usually another array, resulting in a long 2-dimensional array. Speed is crucial for my task, and I'm on the lookout for the fastest solution. It's worth mentioning that in each example, c=[element]
since that's how it appears naturally in my code.
After some research, I've identified a few options. The most basic one is option 1:
function repeatSimple(c, n) {
var arr = [];
for (var i=0; i<n; i++) {
arr = arr.concat(c);
};
return arr;
};
Another alternative was suggested by gdbdmdb in response to a similar question (Concatenate array to itself in order to duplicate it):
function repeatApply(c, n) {
return [].concat.apply([], Array.apply(0, Array(n)).map(function() { return c }));
};
Although these are viable options, I had reservations about both approaches. The first option involves calling concat
multiple times, while the second option seemed complex. Consequently, I devised one more method:
function repeatBinary(c, n) {
var arr = [];
var r = 0;
while (n>0) {
r = n%2;
if (r>0) {
arr = arr.concat(c);
};
n = (n-r)/2;
if (n>0) {
c = c.concat(c);
};
};
return arr
};
This approach minimizes the number of concat
calls to at most 2log_2(n
) times.
Hence, my query remains: Which method offers the quickest way to achieve this task? Are the options I've presented here optimal, or is there a faster solution available? Do all these methods perform similarly in terms of speed, making the choice insignificant?