var newFunc = new Function("let r = Math.random().toString(36).substring(7).includes('x');");
var regular = function(){
return Math.random().toString(36).substring(7).includes('x');;
}
eval("let r = Math.random().toString(36).substring(7).includes('x');");
newFunc();
regular()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
new Function | |
regular |
Test name | Executions per second |
---|---|
eval | 3235167.2 Ops/sec |
new Function | 4779946.0 Ops/sec |
regular | 4768535.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested on MeasureThat.net.
Benchmark Overview
The benchmark consists of three test cases: eval
, new Function
, and regular
. The goal is to compare their performance in executing a specific JavaScript function. We'll break down each test case, explain what's happening under the hood, and discuss pros and cons.
Test Case 1: eval
eval
is a built-in JavaScript function that executes a string as if it were code. In this test case, the string "let r = Math.random().toString(36).substring(7).includes('x');;"
defines a variable r
using a random value generated by Math.random()
. The eval
function then evaluates and returns the result of that expression.
Pros:
Cons:
eval
can execute arbitrary codeTest Case 2: new Function
In this test case, a new function is created using the new Function
syntax. The same string "let r = Math.random().toString(36).substring(7).includes('x');;"
defines a variable r
, just like in the eval
test case.
Pros:
eval
, but with better security guaranteesCons:
eval
Test Case 3: regular
This test case uses a named function expression instead of new Function
or eval
. The same string "let r = Math.random().toString(36).substring(7).includes('x');;"
defines a variable r
, just like in the other two test cases.
Pros:
eval
and new Function
Library/Function Usage
None of these test cases use any external libraries or functions. The focus is on comparing the performance of different JavaScript features.
Special JS Features/Syntax
There are no special JavaScript features or syntax used in this benchmark. It's a straightforward comparison of three simple execution methods.
Alternative Approaches
Other approaches to executing code could include:
String.prototype.execute()
(if supported by the browser)Function()
, without using new
Keep in mind that these alternatives might not be supported by all browsers or environments. MeasureThat.net's focus is on comparing JavaScript features, so it uses a more controlled and standardized approach.
I hope this explanation helps you understand what's happening in the MeasureThat.net benchmark!