Code Optimization Is Tricky

niza

Ebenezer Enietan (Niza)

Posted on July 15, 2023

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
πŸ’– πŸ’ͺ πŸ™… 🚩
niza
Ebenezer Enietan (Niza)

Posted on July 15, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related