Skip to content

Instantly share code, notes, and snippets.

@Jimbly
Created June 9, 2012 04:26
Show Gist options
  • Save Jimbly/2899468 to your computer and use it in GitHub Desktop.
Save Jimbly/2899468 to your computer and use it in GitHub Desktop.
comparing callback binding, calling, closures
function nop() { }
// static functions, .bind them
function doop1(a, cb) { cb(); }
function doop2(a, b, cb) { cb(); }
function backupFile1(filename, cb) {
doop1(filename + '.bak', step2.bind(undefined, filename, cb));
}
function step2(filename, cb, err) {
doop2(filename, filename + '.bak', cb);
}
// closures
function backupFile2(filename, cb) {
doop1(filename + '.bak', function(err) {
doop2(filename, filename + '.bak', cb);
});
}
// functions take a this-pointer
function doop1a(a, cb, thisp) { cb.call(thisp); }
function doop2a(a, b, cb, thisp) { cb.call(thisp); }
function backupFile3(filename, cb) {
doop1a(filename + '.bak', step2a, { fn: filename, cb: cb });
}
function step2a(err) {
doop2a(this.fn, this.fn + '.bak', this.cb);
}
var ii, mem, endmem;
while (true) {
mem = process.memoryUsage().heapUsed;
for (ii = 0; ii < 1000; ++ii) {
backupFile1('a', nop);
}
endmem = process.memoryUsage().heapUsed;
console.log('bind: ' + ((endmem - mem) / 1000));
mem = process.memoryUsage().heapUsed;
for (ii = 0; ii < 1000; ++ii) {
backupFile2('a', nop);
}
endmem = process.memoryUsage().heapUsed;
console.log('closure: ' + ((endmem - mem) / 1000));
mem = process.memoryUsage().heapUsed;
for (ii = 0; ii < 1000; ++ii) {
backupFile3('a', nop);
}
endmem = process.memoryUsage().heapUsed;
console.log('thisp: ' + ((endmem - mem) / 1000));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment