DEV Community

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

Posted on

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

Top comments (0)