Skip to content

Instantly share code, notes, and snippets.

@pasaran
Created October 25, 2012 16:11
Show Gist options
  • Save pasaran/3953729 to your computer and use it in GitHub Desktop.
Save pasaran/3953729 to your computer and use it in GitHub Desktop.
Compare different eval's in node.js
module.exports = function(data) {
var s = '';
s += '<div class="hello">';
s += 'Hello, ' + data.username;
s += '</div>';
return s;
};
function(data) {
var s = '';
s += '<div class="hello">';
s += 'Hello, ' + data.username;
s += '</div>';
return s;
}
#!/bin/bash
echo 'require'
node test-require.js
echo 'function'
node test-function.js
echo 'vm'
node test-vm.js
echo 'eval'
node test-eval.js
var fs = require('fs');
var js = fs.readFileSync('f2.js', 'utf-8');
var f = eval('(' + js + ')');
var data = {
username: 'nop'
};
console.time('a');
for (var i = 0; i < 10000000; i++) {
var r = f(data);
}
console.timeEnd('a');
var fs = require('fs');
var js = fs.readFileSync('f2.js', 'utf-8');
var f = ( new Function('global', '"use strict"; return (' + js + ')') )();
var data = {
username: 'nop'
};
console.time('a');
for (var i = 0; i < 10000000; i++) {
var r = f(data);
}
console.timeEnd('a');
var f = require('./f1.js');
var data = {
username: 'nop'
};
console.time('a');
for (var i = 0; i < 10000000; i++) {
var r = f(data);
}
console.timeEnd('a');
var fs = require('fs');
var vm = require('vm');
var js = fs.readFileSync('f2.js', 'utf-8');
var f = vm.runInNewContext('(' + js + ')');
var data = {
username: 'nop'
};
console.time('a');
for (var i = 0; i < 10000000; i++) {
var r = f(data);
}
console.timeEnd('a');
@alexeyten
Copy link

Обновил ноду

~/Public/gist-3953729|master$ node --version
v0.8.12
~/Public/gist-3953729|master$ ./make.sh 
require
a: 12ms
function
a: 12ms
vm
a: 385ms
eval
a: 446ms

Круто, надо обновлять везде :-)

@pasaran
Copy link
Author

pasaran commented Oct 26, 2012

Потому что eval не джитится. Равно как и runInNewContext видимо.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment