Skip to content

Instantly share code, notes, and snippets.

@mauricemach
Created September 9, 2011 04:13
Show Gist options
  • Save mauricemach/1205485 to your computer and use it in GitHub Desktop.
Save mauricemach/1205485 to your computer and use it in GitHub Desktop.
benchmark of scope manipulation methods in node.js
log = console.log
ben = require 'ben'
vm = require 'vm'
times = 10000
global.sum = (x, y) -> x + y
vm_script = vm.createScript 'console.log(typeof require);', 'vm_script'
new_function = new Function('locals', 'console.log(typeof require);')
applied = -> console.log(typeof require)
log 'typeof require:\n'
log 'runInThisContext:'
vm_script.runInThisContext()
log 'runInNewContext:'
vm_script.runInNewContext {console}
log 'new Function:'
new_function()
log 'apply:'
applied.apply()
vm_script = vm.createScript 'sum(4, 5);', 'vm_script'
new_function = new Function('locals', 'var sum = locals.sum; return sum(4, 5);')
applied = -> @sum 4, 5
log '\nBenchmark:\n'
log 'runInThisContext:', ben times, -> vm_script.runInThisContext()
log 'runInNewContext:', ben times, -> vm_script.runInNewContext {sum}
log 'new Function:', ben times, -> new_function {sum}
log 'apply:', ben times, -> applied.apply {sum}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment