window.case1 = new Proxy({}, {
get(t, p, r) {
if (typeof p === 'string' && !isNaN(p)) {
return +p
}
else {
return Reflect.get(t, p, r)
}
}
});
window.case2 = new Proxy({}, {
get(t, p, r) {
if (/^\d+$/.test(p)) {
return +p
}
else {
return Reflect.get(t, p, r)
}
}
});
window.gabage1 = 0;
window.gabage2 = 0;
for (let i = 0; i < 1e6;i++) { gabage1 =+ case1[i]; }
for (let i = 0; i < 1e6;i++) { gabage2 += case2[i]; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
isNaN | |
regex |
Test name | Executions per second |
---|---|
isNaN | 1.7 Ops/sec |
regex | 1.6 Ops/sec |
I'll break down the provided benchmark definition and test cases to explain what's being tested, compared, and considered.
Benchmark Definition JSON
The Name
field indicates that this benchmark is called "isNumber: regex vs isNaN". The Description
explains that it judges an object property key as a number. Let's dive into the script preparation code:
window.case1 = new Proxy({}, { ... });
: Creates a proxy object (case1
) with a getter function for each property. This getter checks if the property is a string and can be parsed to an integer using isNaN
. If true, it returns the parsed value; otherwise, it returns the original value.window.case2 = new Proxy({}, { ... });
: Similar to case1
, but uses a regular expression (/^\\d+$/
) to check if the property is a number. The regex pattern /^\\d+$/
matches one or more digits (\\d+
) at the start of the string (^
). If true, it returns the parsed value; otherwise, it returns the original value.window.gabage1 = 0;
and window.gabage2 = 0
: These variables are initialized to zero, likely for initialization purposes.The Html Preparation Code
field is empty in this case.
Individual Test Cases
There are two test cases:
for (let i = 0; i < 1e6;i++) { gabage1 =+ case1[i]; }
case1[i]
) to gabage1
. The intention is to measure how many times NaN (Not a Number) is returned when trying to access properties with non-numeric values.for (let i = 0; i < 1e6;i++) { gabage2 += case2[i]; }
^\\d+$
) to check if properties are numbers. The intention is to measure how many times a number is returned when trying to access properties with numeric values.Pros and Cons of Each Approach
^\\d+$
) for validation.Other Considerations
Alternative Approaches
Other alternatives could include:
Number()
function instead of Proxies or regex patterns.lodash
to perform validation.However, these alternatives might not provide a direct comparison to the existing approaches and may add unnecessary complexity.