search
HomeWeb Front-endJS TutorialCompeting with JSON.stringify - by building a custom one

Competing with JSON.stringify - by building a custom one

This came up during a discussion with my friend about Recursion. Why not build
a Javascript JSON.stringify method as a recursive programming exercise? Seems like a great
idea.

I quickly drafted out the first version. And it performed horribly! The
time required was about 4 times that of the standard JSON.stringify.

The first draft

function json_stringify(obj) {
  if (typeof obj == "number" || typeof obj == "boolean") {
    return String(obj);
  }

  if (typeof obj == "string") {
    return `"${obj}"`;
  }

  if (Array.isArray(obj)) {
    return "[" + obj.map(json_stringify).join(",") + "]";
  }

  if (typeof obj === "object") {
    const properties_str = Object.entries(obj)
      .map(([key, val]) => {
        return `"${key}":${json_stringify(val)}`;
      })
      .join(",");
    return "{" + properties_str + "}";
  }
}

By running the following, we can see that our json_stringify works as
expected.

const { assert } = require("console");
const test_obj = {
  name: "John Doe",
  age: 23,
  hobbies: ["football", "comet study"]
};

assert(json_stringify(test_obj) === JSON.stringify(test_obj))

To test more scenarios, and multiple runs to get an average idea of how our
script runs, we made a simple testing script!

A simple testing script

function validity_test(fn1, fn2, test_values) {
  for (const test_value of test_values) {
    assert(fn1(test_value) == fn2(test_value));
  }
}

function time(fn, num_runs = 1, ...args) {
  const start_time = Date.now()

  for (let i = 0; i 


<p>Running this we get the timings like the following.<br>
</p>

<pre class="brush:php;toolbar:false">Testing 1000 times
    Std lib JSON.stringify() took 5 ms
    Custom json_stringify() took 20 ms
Testing 10000 times
    Std lib JSON.stringify() took 40 ms
    Custom json_stringify() took 129 ms
Testing 100000 times
    Std lib JSON.stringify() took 388 ms
    Custom json_stringify() took 1241 ms
Testing 1000000 times
    Std lib JSON.stringify() took 3823 ms
    Custom json_stringify() took 12275 ms

It might run differently on different systems but the ratio of the time taken
by std JSON.strngify to that of our custom json_stringify should be about
1:3 - 1:4

It could be different too in an interesting case. Read on to know more about
that!

Improving performance

The first thing that could be fixed is the use of map function. It creates
new array from the old one. In our case of objects, it is creating an array of
JSON stringified object properties out of the array containing object entries.

Similar thing is also happening with stringification of the array elements too.

We have to loop over the elements in an array, or the entries of an object! But
we can skip creating another array just to join the JSON stringified parts.

Here's the updated version (only the changed parts shown for brevity)

function json_stringify(val) {
  if (typeof val === "number" || typeof val === "boolean") {
    return String(val);
  }

  if (typeof val === "string") {
    return `"${val}"`;
  }

  if (Array.isArray(val)) {
    let elements_str = "["

    let sep = ""
    for (const element of val) {
      elements_str += sep + json_stringify(element)
      sep = ","
    }
    elements_str += "]"

    return elements_str
  }

  if (typeof val === "object") {
    let properties_str = "{"

    let sep = ""
    for (const key in val) {
      properties_str += sep + `"${key}":${json_stringify(val[key])}`
      sep = ","
    }
    properties_str += "}"

    return properties_str;
  }
}

And here's the output of the test script now

Testing 1000 times
        Std lib JSON.stringify() took 5 ms
        Custom json_stringify() took 6 ms
Testing 10000 times
        Std lib JSON.stringify() took 40 ms
        Custom json_stringify() took 43 ms
Testing 100000 times
        Std lib JSON.stringify() took 393 ms
        Custom json_stringify() took 405 ms
Testing 1000000 times
        Std lib JSON.stringify() took 3888 ms
        Custom json_stringify() took 3966 ms

This looks a lot better now. Our custom json_stringify is taking only 3 ms
more than JSON.stringify to stringify a deep nested object 10,000 times.
Although this is not perfect, it is an acceptable delay.

Squeezing out more??

The current delay could be due to all the string creation and concatenation
that's happening. Every time we run elements_str += sep + json_stringify(element)
we are concatenating 3 strings.

Concatenating strings is costly because it requires

  1. creating a new string buffer to fit the whole combined string
  2. copy individual strings to the newly created buffer

By using a Buffer ourselves and writing the data directly there might give us
a performance improvement. Since we can create a large buffer (say 80 characters)
and then create new buffers to fit 80 characters more when it runs out.

We won't be avoiding the reallocation / copying of data altogether, but we will
reducing those operations.

Another possible delay is the recursive process itself! Specifically the
function call which takes up time. Consider our function call json_stringify(val)
which just has one parameter.

Understanding Function calls

The steps would be

  1. Push the return address to the stack
  2. push the argument reference to the stack
  3. In the called function
    1. Pop the parameter reference from the stack
    2. Pop the return address from the stack
    3. push the return value (the stringified part) onto the stack
  4. In the calling function
    1. Pop off the value returned by the function from the stack

All these operations happen to ensure function calls happen and this adds CPU
costs.

If we create a non-recursive algorithm of json_stringify all these operations
listed above for function call (times the number of such calls) would be
reduced to none.

This can be a future attempt.

NodeJs version differences

One last thing to note here. Consider the following output of the test script

Testing 1000 times
        Std lib JSON.stringify() took 8 ms
        Custom json_stringify() took 8 ms
Testing 10000 times
        Std lib JSON.stringify() took 64 ms
        Custom json_stringify() took 51 ms
Testing 100000 times
        Std lib JSON.stringify() took 636 ms
        Custom json_stringify() took 467 ms
Testing 1000000 times
        Std lib JSON.stringify() took 6282 ms
        Custom json_stringify() took 4526 ms

Did our custom json_stringify just perform better than the NodeJs standard
JSON.stringify???

Well yes! But this is an older version of NodeJs (v18.20.3). Turns out, for
this version (and lower also perhaps) our custom made json_stringify works
faster than the standard library one!

All the tests for this article (except this last one) has been done with
Node v22.6.0

The performance of JSON.stringify has increased from v18 to v22. This is so great

It is also important to note that, our script performed better in NodeJs v22.
So, it means, NodeJs has increased the overall performance of the runtime too.
Possibly an update has happened to the underlying V8 engine itself.

Well, this has been an enjoyable experience for me. And I hope it will be for
you too. And in the midst of all this enjoyment, we learnt a thing or two!

Keep building, keep testing!

The above is the detailed content of Competing with JSON.stringify - by building a custom one. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools