Reputation: 1342
In my code, I need to test whether or not a string is empty for millions of times. The question is, which way is better/faster: if str == ''
or if len(str) == 0
. If there's better ways to do this, please share. Any help appreciated.
Upvotes: 1
Views: 117
Reputation: 95338
Please don't name your variables str
, as this is the name of a built-in function.
So if you can be sure that s
is a string (which hopefully is the case), you can just use
if not s:
# s is the empty string
This should be the preferred way of doing such a check. It also works for list
s, set
s and dict
s. Performance-wise, there's probably no noticeable difference, but you can of course measure that to be sure.
Upvotes: 6