2

What are the pros and cons of using the inspect function in node's util module for checking deep object equality, regarding accuracy and performance? I believe it is at least more comprehensive than JSON.stringify()

A few node logs below illustrate the superior accuracy of util.inspect over toString() and JSON.stringify():

> ([1,2, undefined]).toString()
'1,2,'
> ([1,2,null]).toString()
'1,2,'

 JSON.stringify([1,2,null])
'[1,2,null]'
> JSON.stringify([1,2,undefined])
'[1,2,null]'

> require("util").inspect([1,2,undefined])
'[ 1, 2, undefined ]'
> require("util").inspect([1,2,null])
'[ 1, 2, null ]'
> require("util").inspect([1,2,"null"])
'[ 1, 2, \'null\' ]'

But I'm concerned about any gotchas, and also the performance ramifications.

prmph
  • 7,616
  • 11
  • 37
  • 46
  • 1
    IMO using `JSON.stringify()` to deeply compare objects is not a very good idea because it can fail in different ways, starting by stringify itself, for example when there are circular references in the object. Stringify will ignore functions in yout object too – Kaddath May 18 '18 at 10:28
  • Hi @kaddath, yes I know about the issues with JSON.stringify, that is why I am asking about util.inspect as an alternative – prmph May 18 '18 at 10:29
  • Is your goal to only check equality or detect differences? because for the first case, i see there is a function `util.isDeepStrictEqual` that returns a boolean and seems just made for that. For performances you'd have to test, i have no idea, but i feel it should probably be a tiny bit slower than `stringify`, because it has to do extra actions to treat the edge cases `stringify` does not – Kaddath May 18 '18 at 10:37

1 Answers1

0

There are basically two cons to using util.inspect for checking deep object equality:

  • string conversion: unoptimized performance
  • doesn't handle corner cases, eg:
    • util.inspect({x: 10, y: 20}) == '{ x: 10, y: 20 }' but util.inspect({y: 20, x: 10}) == '{ y: 20, x: 10 }' (by the way yes, keys are ordered in ES6)
    • retrieving the same WeakSet entries twice may result in different output

Checking for deep object equality might be 99% successful with JSON.stringify and 99.9% successful with util.inspect but it's precisely this 0.1% of weird corner cases that still makes it unfit for proper production code.

Luckily, util provides isDeepStrictEqual that was designed specifically for deep object equality: it's more performant that util.inspect (no string conversion), makes the code cleaner (instead of comparing converted strings, compare directly the objects using a human-readable function), and handles all the corner cases.

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84