|
|
|
|
|
by to3m
4912 days ago
|
|
NSArray has a constant-time size query, so you might as well do "[x count]==0". If you had a linked list type structure, though, you might just have next/prev pointers in your list object, making a size query an O(N) operation. (The C++ STL provides an "empty()" function in its containers for presumably this reason. It has some containers that have to be implemented as linked lists or trees, meaning there's the possibility that "x.empty()" to be much more efficient than "x.size()==0". Not sure how often implementations take advantage of this, mind.) As for how you'd use it, I've pretty much always used it for early outs: if(items.empty()) return NULL;
return &items[items.size()%rand()];
or for filling in caches: if(items.empty()) return NULL;
if(cache.empty()) { /* fill cache */ }
assert(cache[index].underlying_item==items[index]);
return cache[index].some_other_data;
So it always ends up being tested positively. Or it does if you code like me, anyway :) (I make no statement about whether you should or not.) |
|