1

I would like to know if, when comparing two (potentially massive) strings, JavaScript internally starts by comparing their length before looping over the characters.

If not, would that mean doing something along the lines of

if (string1.length !== string2.length || string1 !== string2)
  // do something if data changed

should lead to a gain of time, right ? (I am assuming the read-only length property of a string is computed when the string is set, and not when asked; Not sure if that's actually the case)

For context, I am dealing with massive strings as I am lazily JSON.stringifying arrays of objects received from some API (comparing the latest element only would probably be better but this question is more out of curiosity than anything, please only mind that the strings I would compare would be humongous ^^)

Relevant references ?

https://javascript.info/comparison

Comparing large strings in JavaScript with a hash

Edit

Thank you @RobG in the comment for linking me to ECMA-262's SameValueNonNumber.

In the step definition, step 5 is

SameValueNonNumber ( x, y )

5.If Type(x) is String, then If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false.

And I think that answers the question

DixiPoowa
  • 133
  • 12
  • 3
    ECMA-262 does not define implementation, only behaviour. When comparing two strings, the [*SameValueNonNumber*](http://ecma-international.org/ecma-262/10.0/#sec-samevaluenonnumber) abstract operation is applied. It would make sense to first check length before comparing code units, but it's not mandatory. – RobG Mar 03 '20 at 09:15
  • Thanks a lot for that link @RobG, it says "_If Type(x) is String, then If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false._". Is it common for some implementation to not fully follow such "behaviour" steps ? (I assume yes, since some browser don't support the same features/implement the same way, but string comparison seems like a very "primitive" function that should be the same everywhere, so I prefer to ask ^^) – DixiPoowa Mar 03 '20 at 09:21
  • @RobG Feel free to post the same comment as an answer so I can close this thread: that link was exactly what I was looking for. I don't know how strictly modern browser follow ECMA's definition but that's ok, I was really looking for the "theory" rather than the actual modern browsers' truth (I'll do some testing to find that out) – DixiPoowa Mar 03 '20 at 09:37
  • As an example, here's the source from [V8's string compare](https://github.com/v8/v8/blob/main/src/objects/string.cc): // Fast check: negative check with lengths. int len = length(); if (len != other.length()) return false; if (len == 0) return true; – antsyawn Jul 05 '22 at 23:48

0 Answers0