function makeTestData() { return 'parentId' }
String(makeTestData());
JSON.stringify(makeTestData());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
toString | |
JSON.stringify |
Test name | Executions per second |
---|---|
toString | 763569.6 Ops/sec |
JSON.stringify | 632876.1 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is being tested?
The benchmark tests two different approaches to convert a JavaScript primitive value (parentId
) to a string:
String()
: This method uses the built-in String constructor to convert the value to a string. It takes ownership of the original value, which means it creates a new string object and copies the original value into it.JSON.stringify()
: This function converts an arbitrary JavaScript value to a JSON string. In this case, it's used to convert the parentId
primitive value to a string.Options compared
The benchmark compares the performance of these two approaches:
String()
(native method)JSON.stringify()
(built-in function)Pros and Cons:
String()
: Pros:JSON.stringify()
: Pros:String()
.Library or special JS feature
There is no specific library used in this benchmark. However, JSON.stringify()
uses the ToString
method on the value being converted, which is a built-in JavaScript method.
Special JS features or syntax (not applicable)
No special JavaScript features or syntax are used in this benchmark.
Other alternatives
Other alternatives to use when converting primitive values to strings include:
${value}
) or concatenation (value + ''
)toJSON()
method (not applicable for primitives)Keep in mind that these alternatives might have different performance characteristics and usage scenarios compared to the built-in String()
and JSON.stringify()
methods.
Benchmark preparation code
The provided script preparation code defines a simple test data function makeTestData()
, which returns the string 'parentId'
. This code is used to generate test data for each benchmark case.