function(){} vs new Function() vs eval(function(){})
JavaScript performance comparison
Info
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope says
Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed every time it is evaluated. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should be avoided whenever possible.
Which sounds bad.
Preparation code
<script>
var fn1 = function() {
return 1 + 2;
};
var fn2 = new Function('return 1 + 2;');
var fn3 = eval('dummy = function(){return 1 + 2;}');
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Function expression |
|
pending… |
Function constructor |
|
pending… |
A function created with eval() |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published by curiousdannii
- Revision 3: published
- Revision 4: published by siR
- Revision 5: published by Simon
- Revision 6: published
- Revision 7: published by Milan Adamovsky
- Revision 8: published by Richard van Velzen
- Revision 10: published by Luigi Grilli
- Revision 11: published
- Revision 12: published by fbender
0 comments