window.case1 = new Proxy({}, {
get(t, p, r) {
if (Number.isInteger(Number(p))) {
return +p
}
else {
return Reflect.get(t, p, r)
}
}
});
window.case2 = new Proxy({}, {
get(t, p, r) {
if (/^-?[0-9]+$/.test(p)) {
return +p
}
else {
return Reflect.get(t, p, r)
}
}
});
window.gabage1 = 0;
window.gabage2 = 0;
for (let i = 0; i < 1e4;i++) { gabage1 =+ case1[i]; }
for (let i = 1.1; i < 1e4;i++) { gabage1 =+ case1[i]; }
for (let i = 0; i < 1e4;i++) { gabage1 =+ case1['qwertyuiop']; }
for (let i = 0; i < 1e4;i++) { gabage1 =+ case1[i]; }
for (let i = 1.1; i < 1e4;i++) { gabage1 =+ case1[i]; }
for (let i = 0; i < 1e4;i++) { gabage1 =+ case1['qwertyuiop']; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Number | |
Regex |
Test name | Executions per second |
---|---|
Number | 90.5 Ops/sec |
Regex | 89.6 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared, and the pros/cons of different approaches.
Benchmark Overview
The benchmark measures the performance difference between two approaches to convert strings to integers:
Number.isInteger()
with a primitive value (+p
) as the conversion method./-?[0-9]+$/.test(p)
) to check if the input string is a valid integer.Script Preparation Code
The script preparation code sets up two proxies, case1
and case2
, with getter functions that return converted values based on the above approaches. The gabage1
variable is initialized twice to measure the overhead of creating new objects for each iteration.
Benchmark Test Cases
There are two test cases:
i < 1e4
) with primitive values and +p
conversion.i < 1e4
) with a valid integer string and the /^-?[0-9]+$/.test(p)
regular expression.Pros and Cons of Each Approach
Library and Syntax
No external libraries are used in this benchmark. However, it does utilize some JavaScript features like:
new Proxy()
)get(t, p, r)
)These features allow for fine-grained control over object behavior and property access, but may be unfamiliar to developers without experience with these aspects of the language.
Other Alternatives
If you were to implement this benchmark using a different approach, some alternatives could include:
parseInt()
or parseFloat()
instead of Number.isInteger()
.regex-escape
for regular expression manipulation.Keep in mind that these alternatives might introduce additional complexity or dependencies, which could affect the benchmark's overall outcome and relevance.