Re:In C++, is empty() faster than comparing the size with zero?
by johntb86 on Thursday October 28, 2021 @02:41PM
(#29029769)
Some
implementations used to be constant-time, since they could just change some pointers in the spliced nodes. Nowadays they take linear time, since they need to count how many nodes are transferred so they can update the sizes correctly.
[ Parent
| on HN ]
Re:In C++, is empty() faster than comparing the size with zero?
by jfrunyon on Thursday October 28, 2021 @05:19PM
(#29032160)
Wouldn't this still be constant-time today? It doesn't need to count the nodes because the other list already has a count of its nodes.
Re:In C++, is empty() faster than comparing the size with zero?
by hermitdev on Thursday October 28, 2021 @05:59PM
(#29032592)
No, because you'd still need book keeping around the length of [first, last), even if the implementation does under-the-hood O(1) movement of nodes in [first, last) from other to *this. Computing the length of [first, last) is still an O(n) operation for forward iterators.
Maybe you're assuming [first, last) is the entirety of other? For that case, there are overloads for splicing an entire list in O(1) time:
void splice( const_iterator pos, list& other );
void splice( const_iterator pos, list&& other );
Re:In C++, is empty() faster than comparing the size with zero?
by jfrunyon on Thursday October 28, 2021 @06:53PM
(#29033074)
This seems like an extremely niche use-case, compared to the prevalence of use-cases needing to check the size of a list.
Re:In C++, is empty() faster than comparing the size with zero?
by ycombobreaker on Thursday October 28, 2021 @08:02PM
(#29033645)
This niche is exactly why I've used std::list in several cases. It allows fairly easy preallocation of list nodes.
Fortunately, the single-node splice is still fast. But batch allocations, say related to some scatter/gather operations, would still be hit by this change.
Re:In C++, is empty() faster than comparing the size with zero?
by MauranKilom on Thursday October 28, 2021 @05:37PM
(#29032368)
No, because you can splice in the middle. Given just the iterators you simply have no other way than counting.
(The reason why it used to be constant time is that it didn't have to count because it didn't have to compute the new size).
Re:In C++, is empty() faster than comparing the size with zero?
by ape4 on Thursday October 28, 2021 @04:16PM
(#29031322)
Interesting, a good case for another std::list<> like std::non_counting_list<>
Re:In C++, is empty() faster than comparing the size with zero?
by ycombobreaker on Thursday October 28, 2021 @08:05PM
(#29033669)
Reminds me of Michael Bolton from Office Space, "Why should I change, he's the one who sucks!"
std::list WAS noncounting. introducing std::counting_list was an option. I didn't follow this decision so I don't know why they opted to break the behavior (performance expectations).