function simpleStringify(o) {
let cache = [];
let data = JSON.stringify(o, function(key, value) {
if (typeof value === "object" && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null;
return data;
}
function verySimpleStringify(o) {
return "{bar:" + o.foo + "}"
}
var testData = {"bar":"foo"}
verySimpleStringify(testData);
simpleStringify(testData);
JSON.stringify(testData)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
verySimpleStringify | |
simpleStringify | |
JSON.stringify |
Test name | Executions per second |
---|---|
verySimpleStringify | 4296300.5 Ops/sec |
simpleStringify | 785889.6 Ops/sec |
JSON.stringify | 1505813.0 Ops/sec |
Let's dive into the explanation.
Benchmark Definition:
The benchmark defines three different stringification functions:
verySimpleStringify(o)
: This function returns a JSON-encoded string with circular references discarded. It uses a custom JSON.stringify method that checks for object properties and discards them if they are already present in a cache.simpleStringify(o)
: This function is similar to JSON.stringify()
, but it doesn't discard circular references. It simply converts the input object into a string without any modifications.JSON.stringify(testData)
: This line uses the built-in JSON.stringify method from JavaScript's standard library, which also does not discard circular references.Options Compared:
The benchmark compares the performance of these three stringification functions on a single test case:
verySimpleStringify
simpleStringify
JSON.stringify
The options compared are the execution speed and efficiency of each function.
Pros and Cons of Each Approach:
verySimpleStringify
because it handles all types of objects without optimization.Libraries Used:
None of the provided code uses any external libraries. The JSON.stringify()
method is a built-in function in JavaScript's standard library.
Special JS Features or Syntax:
This benchmark does not use any special JavaScript features or syntax beyond what is included in the standard library.
Alternatives:
If you want to compare stringification functions, here are some alternative approaches:
String()
instead of JSON.stringify()
, which will simply concatenate all properties into a single string without any formatting.btoa()
and atob()
).Keep in mind that each benchmark should be tailored to a specific use case or problem domain, so you may want to explore different approaches depending on your requirements.