3 ms·
(Also clippy will probably suggest is_empty() over len() == 0)
by steveklabnik 5y ago
(Also clippy will probably suggest is_empty() over len() == 0)
- tialaramex 5y agoI should probably write is_empty() more often, but, it is actually doing anything that len() == 0 isn't doing, or is it just that is_empty() better explains what I presumably wanted to ask?
- spoiler 5y agoI've not looked at the implementation, so I can't answer the first question, but to answer your second point/question: yes! I think getting across intent is very important for the other people reading your code. I guess here it doesn't matter as much since it's a simple enough cases, but I'm just talking in the general sense. With that said, I think is_empty probably has very slightly smaller overhead when it comes to figuring out the author's intent. Because, well, that was the intent. Length checking against 0 is merely a method of that intent. Also, this "intent decoding" while reading code (no pun intended) adds up in mental cost, IMO. So, it wears down the the reader/reviewer attention more quickly.
- steveklabnik 5y agoFrom clippy’s docs: > Some structures can answer .is_empty() much faster than calculating their length. So it is good to get into the habit of using .is_empty(), and having it is cheap. Besides, it makes the intent clearer than a manual comparison in some contexts. It also has a lint for implementing both methods if you’ve only defined one, to help perpetuate the convention.