DEV Community

Cover image for Code Optimization Is Tricky
Ebenezer Enietan (Niza)
Ebenezer Enietan (Niza)

Posted on

3

Code Optimization Is Tricky

I want you to look at the code below and guess which code will run faster. The console.time() method starts a timer you can use to track how long an operation takes. After guessing run the script and check your console to find out which one runs faster let me know if you guessed right

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>speed test</title>
</head>
<body>
  <h1>check your console</h1>
  <script>
    console.time("first");
      console.groupCollapsed()
      let count = 2;
      while( count <= 5000){
        if(count % 2 == 0 ){
          console.log(count);
        }
        count ++;
      }
      console.groupEnd()
    console.timeEnd("first");


    console.time("second");
      console.groupCollapsed()
      let trick = 2;
      while( trick <= 5000){
        console.log(trick);
        trick += 2;
      }
      console.groupEnd()
    console.timeEnd("second");
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay