Skip to content

Instantly share code, notes, and snippets.

@joenoon
Created September 28, 2011 08:24
Show Gist options
  • Save joenoon/1247348 to your computer and use it in GitHub Desktop.
Save joenoon/1247348 to your computer and use it in GitHub Desktop.
avoid deepening the javascript stack
// the biggest problem i've faced in "big" js apps (one-page RIAs, mobile and web)
// is the javascript stack. avoid diving deep as much as possible. basically
// a function that calls a function that calls a function within a loop is a
// really really bad idea. especially on mobile devices that typically don't have
// a stack limit as big as a normal browser.
var books = [
{ name: "A", chapters: [ { name: "X" }, { name: "Y" }, { name: "Z" } ] },
{ name: "B", chapters: [ { name: "X" }, { name: "Y" }, { name: "Z" } ] },
{ name: "C", chapters: [ { name: "X" }, { name: "Y" }, { name: "Z" } ] },
{ name: "D", chapters: [ { name: "X" }, { name: "Y" }, { name: "Z" } ] },
{ name: "E", chapters: [ { name: "X" }, { name: "Y" }, { name: "Z" } ] }
];
doSomethingWithBookAndChapter = function (book_name, chapter_name) {
console.log(book_name, chapter_name);
};
// this isnt the best example, because forEach is native. things get much worse
// with non-native each() and map() functions found in various libraries. but
// even so, forEach still increases the stack depth
books.forEach(function (book) { // 1 call, top level of stack
book.chapters.forEach(function (chapter) { // 5 calls (each book), 1 level deep in stack
doSomethingWithBookAndChapter(book.name, chapter.name); // 15 calls (3 chapters per book), 2 levels deep in stack
});
});
// same thing, uglier code, but does not increase the stack
var book, chapters, chapter, bi, bl, ci, cl;
for (bi = 1, bl = books.legth; bi < bl; bi++) {
book = books[bi];
chapters = book.chapters;
for (ci = 1, cl = chapters.legth; ci < cl; ci++) {
chapter = chapters[ci];
doSomethingWithBookAndChapter(book.name, chapter.name); // 15 calls, top level of stack
}
}
// same thing again, in coffeescript, compiles pretty much to the bare-metal example directly above
for book in books
for chapter in book.chapters
doSomethingWithBookAndChapter(book.name, chapter.name)
// now you see why i like coffeescript so much :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment