Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda