eval("99999999999999999999999999999999999999999999999999999999999999999999999999");
parseInt("99999999999999999999999999999999999999999999999999999999999999999999999999");
eval("999");
parseInt("999");
Number('999');
Number('99999999999999999999999999999999999999999999999999999999999999999999999999');
JSON.parse('999');
JSON.parse('99999999999999999999999999999999999999999999999999999999999999999999999999');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
long eval() | |
long parseInt() | |
short eval() | |
short parseInt() | |
short Number class call | |
long Number class call | |
short JSON.parse | |
long JSON.parse |
Test name | Executions per second |
---|---|
long eval() | 9437932.0 Ops/sec |
long parseInt() | 9259825.0 Ops/sec |
short eval() | 9456455.0 Ops/sec |
short parseInt() | 143379984.0 Ops/sec |
short Number class call | 144277200.0 Ops/sec |
long Number class call | 128639104.0 Ops/sec |
short JSON.parse | 18264910.0 Ops/sec |
long JSON.parse | 4173189.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The benchmark measures the performance of three different ways to parse or convert numbers:
eval()
: executes a string as JavaScript code.parseInt()
: converts a string to an integer value.Number()
: creates a new number object from a string.JSON.parse()
: parses a JSON string into a JavaScript object.These functions are used to parse or convert numbers, which can be useful in various scenarios such as handling user input, processing data from APIs, or validating user-generated content.
Comparison of options
The benchmark compares the performance of these four options for different types and lengths of input:
eval()
(single-digit number)eval()
(long string representation of a large number)parseInt()
parseInt()
Number
class callNumber
class callJSON.parse()
JSON.parse()
Pros and Cons
Here's a brief summary of the pros and cons for each option:
parseInt()
.Library usage
In this benchmark, no specific libraries are used except for the built-in JavaScript functions mentioned above.
Special JS features or syntax
There are no special JavaScript features or syntax being tested in this benchmark. The focus is on comparing the performance of different parsing and conversion methods.
Now that we've covered the basics, let's talk about alternative approaches:
Other alternatives to these four options include:
lodash
for parsing numbers, which can provide additional functionality and flexibility.Number('0x...')
) if applicable.However, these alternatives are not part of this specific benchmark and would require additional code changes to accommodate.