Guest User

Untitled

a guest
Jul 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. var vm = require('vm'),
  2. code = 'var square = n * n;',
  3. fn = new Function('n', code),
  4. script = vm.createScript(code),
  5. sandbox;
  6.  
  7. n = 5;
  8. sandbox = { n: n };
  9.  
  10. benchmark = function(title, funk) {
  11. var end, i, start;
  12. start = new Date;
  13. for (i = 0; i < 5000; i++) {
  14. funk();
  15. }
  16. end = new Date;
  17. console.log(title + ': ' + (end - start) + 'ms');
  18. }
  19.  
  20. benchmark('vm.runInThisContext', function() { vm.runInThisContext(code); });
  21. benchmark('vm.runInNewContext', function() { vm.runInNewContext(code, sandbox); });
  22. benchmark('script.runInThisContext', function() { script.runInThisContext(); });
  23. benchmark('script.runInNewContext', function() { script.runInNewContext(sandbox); });
  24. benchmark('fn', function() { fn(n); });
  25.  
  26. /*
  27. vm.runInThisContext: 12ms
  28. vm.runInNewContext: 2210ms
  29. script.runInThisContext: 7ms
  30. script.runInNewContext: 2199ms
  31. fn: 0ms
  32. */
Add Comment
Please, Sign In to add comment