Created
February 28, 2015 16:21
-
-
Save ssnau/b0bf4db8f630e2fb68d3 to your computer and use it in GitHub Desktop.
var benchmarking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function benchmark(func){ | |
var s = Date.now(); | |
var obj = {a: 1, b: 2}; | |
Array(10000).join(' ').split('').forEach(function(){ | |
func('c = a * b', obj) | |
func('c', obj) | |
}); | |
var e = Date.now(); | |
console.log( 'total cost:' + (e - s)); | |
} | |
var cache1 = {}; | |
function evaltest(expression, obj) { | |
if (!cache1[expression]) { | |
cache1[expression] = evalcompile(expression); | |
} | |
return cache1[expression](obj); | |
} | |
function evalcompile(expression) { | |
return function(obj) { | |
var x = null; | |
try { | |
with (obj) { | |
x = eval('(' + expression + ')'); | |
} | |
} finally { | |
return x; | |
} | |
}; | |
} | |
var cache = {}; | |
function compiletest(expression, obj) { | |
if (!cache[expression]) { | |
cache[expression] = compile(expression); | |
} | |
return cache[expression](obj); | |
} | |
var re_vars = /(['"\/]).*?[^\\]\1|\.\w*|\w*:|\b(?:(?:new|typeof|in|instanceof) |(?:this|true|false|null|undefined)\b|function *\()|([a-z_$]\w*)/gi; | |
function wrap(s, nonull) { | |
s = s.trim() | |
return !s ? 'void 0' : '(function(v){try{\n v=' | |
// prefix vars (name => data.name) | |
+ (s.replace(re_vars, function(s, _, v) { return v ? 'd.'+ v : s }) | |
// break the expression if its empty (resulting in undefined value) | |
|| 'x') | |
+ '\n}finally{\nreturn v;' | |
+ '}}).call(d)' | |
} | |
function compile(expression) { | |
return new Function('d', 'return ' + wrap(expression)); | |
} | |
benchmark(evaltest); | |
benchmark(compiletest); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment