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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE