Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!