Skip to content

Instantly share code, notes, and snippets.

@EyalAr EyalAr/README.md
Last active Aug 29, 2015

Embed
What would you like to do?
Benchmarks of various nested loops control flow mechanisms in Javascript

MDN recommends NOT to use labels in Javascript, and instead use exceptions or functions. But turns out labels are the fastest, closely followed by named functions.

Test case: Run two nested loops. The inner loop needs to continue the outer loop upon some condition.

Tests:

  1. Using named loops with labels.
  2. Using an anonymous function.
  3. Using a named function.
  4. Using exceptions.

Results:

$ time node labels.js

real    0m0.138s
user    0m0.130s
sys     0m0.008s

###################

$ time node anon_func.js

real    0m0.631s
user    0m0.623s
sys     0m0.011s

###################

$ time node named_func.js

real    0m0.163s
user    0m0.155s
sys     0m0.007s

###################

$ time node throw.js

real	0m1.868s
user	0m1.860s
sys     0m0.018s
var ITERATIONS = 10E6,
tmp = 0;
// OUTER LOOP
for (var i = 0; i < ITERATIONS; i++) {
(function() {
// INNER LOOP
for (var j = 0; j < ITERATIONS; j++) {
if (j > 10) return;
}
// CODE TO SKIP
tmp++;
})();
}
var ITERATIONS = 10E6,
tmp = 0;
// OUTER LOOP
outer: for (var i = 0; i < ITERATIONS; i++) {
// INNER LOOP
inner: for (var j = 0; j < ITERATIONS; j++) {
if (j > 10) continue outer;
}
// CODE TO SKIP
tmp++;
}
var ITERATIONS = 10E6,
tmp = 0;
// OUTER LOOP
for (var i = 0; i < ITERATIONS; i++) inner();
function inner() {
// INNER LOOP
for (var j = 0; j < ITERATIONS; j++) {
if (j > 10) return;
}
// CODE TO SKIP
tmp++;
}
var ITERATIONS = 10E6,
tmp = 0;
// OUTER LOOP
for (var i = 0; i < ITERATIONS; i++) {
try {
// INNER LOOP
for (var j = 0; j < ITERATIONS; j++) {
if (j > 10) throw 0;
}
} catch (e) {
continue;
}
// CODE TO SKIP
tmp++;
}
@StoloADiane

This comment has been minimized.

Copy link

commented Jul 29, 2015

http://stackoverflow.com/questions/4906762/is-using-labels-in-javascript-bad-practice
That text was removed from MDN in May 2015, with these comments in the revision history: "Removing recommandation not supported by clear evidence." "Clearing technical review. I think it is true that there is no need for the big red banner that discourages labels. Havent found anything that says differently." –

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.