According to this answer, the time complexity of JSON.parse()
is O(n)
.
Does this hold true for JSON.stringify()
? There does not appear to be anywhere that documents this.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
JSON is very simple grammar that does not require even lookaheads. As soon as GC is not involved then it is purely O(n) .
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
stringify does not act like an "identity" function when called on data that has already been converted to JSON. By design, it will escape quote marks, backslashes, etc. You need to call JSON. parse() exactly as many times as you called JSON.
It should be O(n), but n
is the number of nodes in the entire object hierarchy of the value being stringified. So if you have an array of numbers, n
is array.length
. But if you have an object like:
var obj =
{ a: [1, 2, 3],
b: { x: 1, y: z },
c: { q: [1, 2], r: "abc" }
}
n
is 3 (properties of obj
) + 3 (elements of obj.a
) + 2 (elements of obj.b
) + 2 (elements of obj.c
) + 2 (elements of obj.c.q
) = 12
This also treats stringifying strings as constant, but in actuality they're O(n) where n` is the length of the string. But unless you have lots of long strings in the object, the difference is probably not significant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With