Home > Software design >  The most optimized way to copy and duplicate elements of an array into new one
The most optimized way to copy and duplicate elements of an array into new one

Time:08-22

What's the most optimized way to copy and duplicate an array into a new one, so arr1 = [1,2] becomes arr2 = [1,2,1,2]?

I can do this:

for(let a of arr1){
    arr2.push(a)
}
for(let a of arr1){
    arr2.push(a)
}

Is there a more optimized way to do it with a more efficient time complexity?

CodePudding user response:

I just benchmarked your loops vs. const arr2 = [...arr1, ...arr1] with 100k items in an array in Chrome. The results:

For loops: 291 ops/s
Ellipsis:  513 ops/s

So [...arr1, ...arr1] was faster by 43%. You can go ahead and test further in other browsers and/or different array size.

CodePudding user response:

Use Array.concat() works in 30% of the time taken by ...Array which takes about 66% of the time taken by Array.push()

The test below uses an array with 10,000 elements and logs the total times taken to perform each method 100,000 times. It takes about 30s to complete the tests on my machine. I get results like:

wait for it ...
push: 14853
spread: 9332
concat: 3063

const n = 100000
const a = [...Array(n/10).keys()]

console.log("wait for it ...")
const concatTest = () => {
  let b

  const s = Date.now() // go
  for (let i = 0; i < n; i  ) {
    b = a.concat(a)
  }
  console.log('concat:', Date.now() - s) // time

}

const spreadTest = () => {
  let c

  const t = Date.now() // go
  for (let j = 0; j < n; j  ) {
    c = [...a, ...a]
  }
  console.log('spread:', Date.now() - t) // time

  concatTest()
}
const pushTest = () => {
  let d

  const u = Date.now() // go
  for (let k = 0; k < n; k  ) {
    d = []
    for (let x of a) {
      d.push(x)
    }
    for (let x of a) {
      d.push(x)
    }
  }
  console.log('push:', Date.now() - u) // time

  spreadTest()
}
pushTest()

CodePudding user response:

I think the following will do:

const arr2 = [...arr1, ...arr1]

OR

 const arr2 = arr1.concat(arr1)

CodePudding user response:

Your time complexity here is O(N) (while you do 2N operations, we ignore the constant 2), where N is the size of arr. A more optimized time-complexity would mean making your code run in sublinear time, which isn't possible here as you need to look at each number in arr1 at least once to be able to push it into your new array. You can do some tweaks to improve the runtime of your code overall (as other answers have shown), but that will not improve the time complexity of your solution (as they are two different things).

  • Related