Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
The most optimized way to copy and duplicate elements of an array into new one

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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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()

about 4 years ago · Juan Pablo Isaza Relatório

0

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).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda