myString.isEmpty vs myString = ""

Years ago I used the second = “” way of checking if a string was empty.
But a while ago I switched to the isEmpty method.

Is there actually an advantage of using the .isEmpty function?

the first make a string compare and the other test the length. theoretically

I would have hoped that if comparing to an empty string the compiler would optimise that to checked the string’s length but perhaps it doesn’t in default mode.

I’d wish the compiler would optimize isEmpty, Len = 0 or Lenb = 0 or = “” checks to a simple nil check.

Doing a quick test in a loop that’s run 1,000,000 times IsEmpty takes a whopping 7 microseconds longer when running in the debugger. I’d call it a wash. Use whatever feels more comfortable to you.

IsEmpty seems to check Length function, so just don’t use it and check length yourself to save one function call internally.

1 Like

I could not find a Feedback case, so I made one:

64074: Optimize compiler for string compare to being empty.

1 Like

I don’t know if it’s still true, but I tested years ago and s = "" was faster than s.LenB = 0. s.Len (or s.Length) is the slowest because it has to count Unicode characters.

Does it not keep a length internally when a string is created or modified?

The length in bytes is in a field.
The length of characters needs to be calculated.

Based on observation during past tests, no. But I don’t know if that has changed. Since strings are immutable, it would make sense, but maybe it does that after first access or something, I don’t know.

I do know that I avoid use Length where speed is a factor.