Search code examples
javascriptperformanceloopsobjectoptimization

JS Optimization/Performance: Comparing objects using JSON.stringify


I'm currently building a small application is Vanilla JS (without any dependencies like lodash/jquery) and I needed to compare two objects to check for equality in keys and values. I was just wondering about how to optimize this problem.

The keys of both objects are in the same order as they are derived from the same method. According to this answer, the fastest and most efficient way to do this is using JSON.stringify(object1) === JSON.stringify(object2).

However, in my app, if the two objects are not equal, then I loop through the two of them and perform some operations. The problem is that these operations are pretty performance heavy and run occasionally. I need to optimize my solution.

Therefore, I was wondering if JSON.stringify runs some sort of for loop internally as well. In my application, it is more likely for the two objects to be unequal. Therefore, if JSON.stringify also runs some sort of for loop, I could just remove the check and run the operations I need right away (which will only cause a difference in the program if the two objects are unequal) saving time and making it more optimized. If I don't do this, then I will technically be running two for loops for the exact same purpose when the two objects are unequal and running one for loop either way when the two objects are equal. If JSON.stringify is some sort of for loop internally, then I can just one for loop no matter if the objects are equal. Am I making sense here? Please let me know if you don't understand something. Is this check useless and should I remove it to optimize my code?


Solution

  • Your question touches 4 different areas:

    • The implementation (and thus performance) of JSON.stringify
    • The implementation (and thus performance) of object iteration
    • The quality and performance of the JIT compiler
    • The speed of memory allocation (JSON.stringify is a memory hog for big objects)

    So it is quite clear, that there is no "Universal" answer for all JS engines and OSes.

    I recommend you do checks in your code ... why?

    • While right now the order of attributes might be constant, future maintenance to your codebase might change that and introduce a hard to track down bug.
    • It is good practice to create an isEqual method for all object types you use
    • It is better readable.

    Of course there are also disadvantages:

    • Your code will become bigger (this might be linked to better readable)
    • Anything else I might have forgotten.