0

I am trying to implement generators in Node.js. I came across node-fiber and node-lazy. Node-lazy deals with arrays and streams, but does not generate lazy things inherently (except numbers).

While using fiber looks cleaner, it has its cons, and as such, I prefer pure Javascript with closures as it's more explicit. My question is: are there memory or perf problems using closure to generate an iterator?

As an example, I'm trying to iterate through a tree depth-first, for as long as the caller asks for it. I want to find 'waldo' and stop at the first instance.

Fiber:

var depthFirst = Fiber(function iterate(tree) {
    tree.children.forEach(iterate);
    Fiber.yield(tree.value);
});

var tree = ...;
depthFirst.run(tree);
while (true) {
    if (depthFirst.run() === 'waldo')
        console.log('Found waldo');
}

Pure JavaScript with closures:

function iterate(tree) {
    var childIndex = 0;
    var childIter = null;
    var returned = false;
    return function() {
        if (!childIter && childIndex < tree.children.length)
            childIter = iterate(tree.children[childIndex++]);

        var result = null;
        if (childIter && (result = childIter()))
            return result;

        if (!returned) {
            returned = true;
            return tree.value;
        }
    };
}

var tree = ...;
var iter = iterate(tree);
while (true) {
    if (iter() === 'waldo')
        console.log('found waldo');
}
Community
  • 1
  • 1
Oliver Zheng
  • 7,831
  • 8
  • 53
  • 59
  • I don't know about performance (the question should be: is performance an issue in the first place?), but V8 engine (which Node.JS uses) is quite smart and there shouldn't be any memory leaks. – freakish Apr 11 '13 at 08:27
  • 1
    It seems likely that Fiber's internal workings are a highly abstracted form of the pure js solution. If both versions work and there's no clear evidence of performance/leakage issues, then maybe it comes down to maintainability. Personally, I would prefer to be given the pure javascript to maintain as I wouldn't have to to do an hour's reading before touching the code. Similarly, if I was the manager or section-leader, I would prefer pure js because there's a greater chance of finding a programmer who could do the work. – Beetroot-Beetroot Apr 11 '13 at 22:19

0 Answers0