Reputation: 38667
I'd like to know which one is fastest for testing a non-empty NSString for iOS 7.0+.
Note: the strings to test will be 99% of the time from 2 to 100 chars length.
if ([foo length] > 0)
or
if ([foo isEqualToString:@""] == NO && foo != nil)
I think it depends if isEqualToString:
compares the length first (and in that case first way is faster) or if isEqualToString:
compares first character of strings first (and in that case second way might be faster).
ps: I already know isEqualToString:
is faster than isEqual:
which is itself faster than compare:
.
Upvotes: 3
Views: 809
Reputation: 104698
Simply testing the length is multiple times faster (on the system i tested).
Of course, you're relying on the framework implementation.
You might consider a function, which could improve readability, and if the "fast way" changes, you will have only 2 lines to change.
In the comments below, I suggested that using a constant/singular/unique string would be the fastest for comparison.
isEqualToString:
onlylength
length
(half elements in test matched constant). this would apply if some of your collection's empty strings were the constant, but some were not. can vary based on distribution of constant in collection.Using pointer comparison is 5x faster than testing the length, and 15.7x times faster than isEqualToString:
. Of course, you may need to add some overhead when creating your array to ensure all your empty strings are the constant.
Upvotes: 3
Reputation: 15813
Measure it and see.
Seriously. You shouldn't be optimising for stuff like this unless you can see it is actually a performance bottleneck (which is pretty unlikely). If instruments (use the time profiler) is telling you that it's an issue, then the correct approach is to MEASURE your assumptions.
Generate n million random strings, time the code using option A then option B and choose the fastest.
Upvotes: 4