let number = +'100'
let number = parseInt('100')
let str = "" + 100
let str = String(100)
let number = Number("100")
let bool = !!1
let bool = Boolean(1)
let str = new String(100)
let number = new Number("100")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Number +'100' | |
Number parseInt | |
String "" + 100 | |
String String100 | |
Number Number | |
Boolean !!1 | |
Boolean Boolean | |
String new String | |
Number new Number |
Test name | Executions per second |
---|---|
Number +'100' | 88133416.0 Ops/sec |
Number parseInt | 83477624.0 Ops/sec |
String "" + 100 | 79237176.0 Ops/sec |
String String100 | 57016988.0 Ops/sec |
Number Number | 81657064.0 Ops/sec |
Boolean !!1 | 95986600.0 Ops/sec |
Boolean Boolean | 83972240.0 Ops/sec |
String new String | 86664720.0 Ops/sec |
Number new Number | 37461820.0 Ops/sec |
The benchmark defined as "Type coercion benchmark 2" is designed to measure the performance of various JavaScript approaches for type coercion, specifically converting values between different types such as strings, numbers, and booleans. Each test case evaluates a distinct method of type conversion, which helps provide insight into the efficiency and performance characteristics of each method under similar conditions.
Number +'100'
+
operator, which coerces the string '100'
into the number 100
.+
.Number parseInt('100')
parseInt
, which converts a string to an integer, starting from the leftmost character.parseInt('10.5')
results in 10
).parseInt
can truncate decimal values).String "" + 100
100
, converting it to a string '100'
.+
.String String(100)
String
function to create a string representation of the number 100
.Number Number("100")
+
, but uses the Number
constructor for conversion.+
directly.Boolean !!1
1
into a boolean true
.Boolean Boolean(1)
Boolean
constructor to create a boolean from 1
, yielding true
.String new String(100)
String
constructor to create an object wrapper for the string '100'.Number new Number("100")
new String
, it can be useful in specific contexts requiring an object.The benchmark results show that the methods involving direct coercion (e.g., unary +
, or concatenation with an empty string) performed the best, achieving high execution rates per second (over 95 million for some cases). In contrast, methods that create objects (new String
, new Number
) performed the worst, demonstrating significantly lower execution rates (in the low 38 million range).
Other alternatives for type coercion in JavaScript could include:
`${100}`
could also be used to convert numbers to strings.Number.isFinite
or Number.isNaN
for validation after coercion to handle edge cases more effectively.In summary, while JavaScript offers various methods for type coercion, the choice of method can impact both performance and readability. It is beneficial for developers to consider the context and requirements of their specific use cases when selecting the most appropriate approach.