V8 performance inside try/catch

Date: 16 Apr 2012
Author: Erik Dubbelboer

I have learned recently that V8, the javascript engine behind nodejs can’t optimize inside a try/catch block. Just look at the running times of the next two examples:

function test() {
  try {
    for (var i = 0; i < 1000000000; ++i) {
      if (i % 2) {
        ;
      }
    }
  } catch (e) {
  }
}

test();

This example takes on average 9 seconds to complete.

function test() {
  for (var i = 0; i < 1000000000; ++i) {
    if (i % 2) {
      ;
    }
  }
}

try {
  test();
} catch (e) {
}

While this very similar example takes an average of 1.7 seconds to complete.

function test() {
  for (var i = 0; i < 1000000000; ++i) {
    try {
      if (i % 2) {
        ;
      }
    } catch (e) {
    }
  }
}

test();

Setting up a try/catch frame is also very expensive as can be seen by this example taking an average of 11 seconds.

comments powered by Disqus