DEV Community

Tanuja
Tanuja

Posted on

2 1

Speedup your javaScript code using this for loops , analysis using "benchmarkjs" tool.

Hello, programmers and enthusiastic learner, hope you all having great day. So in last post I had analyze execution time of various loops in javaScript using console object. Today I am going to analyze it using benchmarkjs tool , thanks for Conner Peet for his valuable suggestion.
So let's start...


const cars = ["Tesla", "Tata", "Ford", "Land Rover", "Audi"];

let myCars;

//For-let loop
bench("for-let i++", () => {
  for (let i = 0; i < cars.length; i++) {
    myCars = cars[i];
  }
});

//For-let (i--) loop
bench("for-let i--", () => {
  for (let i = cars.length - 1; i >= 0; i--) {
    myCars = cars[i];
  }
});

//forEach Loop
bench("forEach", () => {
  cars.forEach((car) => {
    myCars = car;
  });
});

//For of loop
bench("for of", () => {
  for (const car of cars) {
    myCars = car;
  }
});

//For in loop
bench("for in", () => {
  for (const car in cars) {
    myCars = car;
  }
});

//map
bench("map", () =>
  cars.map((car) => {
    myCars = car;
  })
);

//Output

D:\JavaScript\Loops> matcha loops.js

         12,200,000 ops/sec > for-let i++ (24.4x)
         10,300,000 ops/sec > for-let i-- (20.6x)
         11,200,000 ops/sec > forEach (22.4x)
          7,080,000 ops/sec > for of (14.1x)
            502,000 ops/sec > for in (1x)
          5,760,000 ops/sec > map (11.5x)

  Benches: 6
  Fastest: for-let i++
  Elapsed: 35.5s


Enter fullscreen mode Exit fullscreen mode

I used this tool, by Conner Peet.
Hope this article add some value to your skill , Your precious suggestions and advice are always welcome!

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay