Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of JSON.stringify()?

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.

like image 810
MirroredFate Avatar asked Jul 11 '18 22:07

MirroredFate


People also ask

What is JSON Stringify () method?

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.

What is time complexity for JSON parse?

JSON is very simple grammar that does not require even lookaheads. As soon as GC is not involved then it is purely O(n) .

What is the output of JSON Stringify?

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.

Does JSON Stringify escape quotes?

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.


1 Answers

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.

like image 169
Barmar Avatar answered Oct 28 '22 08:10

Barmar