var bigdata = {};
for (var i = 0; i < 100; i++) {
var usdata = {
name: 'user' + i,
surname: 'user' + i,
friends: {}
};
for (var j = 0; j < 10; j++) {
usdata.friends['friend' + j] = {
_ref: 'firend' + j
};
}
bigdata['user' + i] = usdata;
}
var str = JSON.stringify(bigdata);
var str = JSON.stringify(bigdata, function(k,v) { return (k.charAt(0) == '$') ? undefined : v; });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Plain JSON stringify | |
With filter |
Test name | Executions per second |
---|---|
Plain JSON stringify | 1503.6 Ops/sec |
With filter | 675.8 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what's being tested.
Benchmark Definition
The benchmark definition is a JSON object that contains two scripts: Script Preparation Code
and Html Preparation Code
. The Script Preparation Code
section creates an object called bigdata
with 100 users, each having 10 friends. This object is then used to test the performance of the JavaScript JSON.stringify()
function.
The Json Preparation Code
section defines two different benchmark definitions:
JSON.stringify()
function without any filters.undefined
if the key starts with $
.Options compared
Two options are being compared in this benchmark:
JSON.stringify()
function, which recursively converts all properties of an object to strings.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Library and purpose
There is no specific library mentioned in the benchmark definition. However, it's worth noting that JSON.stringify()
uses the native JavaScript implementation, which relies on the ECMAScript standard.
Special JS feature or syntax
The custom filter function used in the "With filter" test case employs a technique called key filtering, where only certain keys are included in the output string. This is achieved using the function(k,v) { return (k.charAt(0) == '$') ? undefined : v; }
callback.
In this specific implementation, the filter function checks if the key (k
) starts with a $
character and returns undefined
if it does. If the key does not start with a $
, the value (v
) is passed through unchanged. This effectively removes keys that start with a $
from the output string.
Other alternatives
If you're interested in exploring alternative approaches, here are some options:
JSON.stringify()
is native to JavaScript, there are libraries like Lodash's lodash.stringify()
or JSON Stringifier that can provide more advanced features and customizations.Object.keys()
, forEach()
, and String.prototype
methods.Keep in mind that these alternatives may introduce additional complexity or performance overhead, so it's essential to evaluate their trade-offs carefully.