The String type is Swift has a property named isEmpty
that indicates whether a string has no characters.
I'd like to know if there's any difference between using isEmpty
and checking the equality to an empty string literal. In other words, is myString.isEmpty
any better than myString == ""
?
I did some research and came across the following recommendations:
- String struct reference at Apple developer documentation (as well as the Swift Language Guide) recommends using
isEmpty
instead of checking the string's length:
To check whether a string is empty, use its
isEmpty
property instead of comparing the length of one of the views to0
. Unlike with isEmpty, calculating a view’s count property requires iterating through the elements of the string.
Answer to a slightly different question from 2015 on StackOverflow by Rob Napier states the following:
The empty string is the only empty string, so there should be no cases where
string.isEmpty()
does not return the same value asstring == ""
. They may do so in different amounts of time and memory, of course. Whether they use different amounts of time and memory is an implementation detail not described, butisEmpty
is the preferred way to check in Swift (as documented).Some blog posts also recommend using
isEmpty
especially instead of checking if the string's length is 0.
None of these sources however say anything against comparing with an empty literal.
It seems totally reasonable to avoid constructions like myString.count == 0
because of obvious performance and readability drawbacks. I also get the fact that myString.isEmpty
is more readable than myString == ""
.
Still, I'm curious whether the comparison with an empty string literal is bad. Does it really have any memory or performance implications? Perhaps the Swift compiler is so smart these days that it will produce the same binary code for myString.isEmpty
and myString == ""
? My gut feeling is that the difference should be negligible or even non-existent but I don't have proofs.
I realize it's not really a practical question though, however I'll be grateful if someone could share some insights how these two alternatives work on a lower level and whether there are any differences. Thank you all in advance.