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

210
Visualizações
Initializing array as is vs doing array.push(item) in javascript

Is there any performance difference between doing:

const array = [1, 2]

and

const array = []
array.push(1);
array.push(2);

I think the latter is more readable. I read that array.push() is faster in some browsers compared to doing array[n] = item, but did not find anything about initializing with the element as is. Are they both O(1) operations? Is there a downside to doing the latter?

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

0

The first method (const array = [1, 2]) is more performant, as there are fewer operations.

After running a quick benchmark to back this up, it appears that the second method is 95% slower! (based on approximately 736026k ops per sec, as opposed to 27184k ops per sec)


Here's a rudimentary demo which outputs how long (in milliseconds) that it takes to run each operation 1 million times.

const NUM_ITTERATIONS = 1000000;

// TC 1: Initializing an Array
function testCase1() {
 const array = [1, 2]
}

// TC 2: Using Array.push()
function testCase2() {
 const array = []
  array.push(1);
  array.push(2);
}

// Start timer, run given function x time, then end timer
const runPerformanceTest = (testCase, msg) => {
  const startTime = performance.now();
  let n = 0;
  while (n < NUM_ITTERATIONS) {
    testCase();
    n++;
  }
  const endTime = performance.now();
  const totalTime = endTime - startTime;
  console.log(`${msg}: ${totalTime} ms`);
}

// Kick of the test for each function + print results
runPerformanceTest(testCase1, 'Test Case 1');
runPerformanceTest(testCase2, 'Test Case 2');

Alternatively, here's a longer benchmark: https://jsbench.me/msl33e4b6k/1

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