Recently I needed to write a code, which fills a list, but sometimes removes some elements from its end. I.e. the following workflow:
I implemented removal of the list's tail as follows:
list.size = savedSize
Since savedSize is always less than current size of the list, I expected this to be an efficient operation. However, I got a major performance leak here. That's because I missed the fact that "changing size automatically allocates new storage so that capacity exactly matches the new size." So, on every assignment, I got the whole list copied.
Of course, this was my fault. The efficient implementation would be as follows:
But, for what reason changing size changes capacity? We have enough methods to shrink the capacity ('capacity' field, trim method). Why to have such side effect on changing size?
I think, this is a counterintuitive behavior. My point is a developer is likely to assume that setting list's size to a lesser value should be very fast operation. It's the most natural way to remove tail of a list. It seems so easy, that a developer may be fooled (like me) and forget about that it's very costly.
Well I can see that viewpoint. I originally wrote it that way because I figured if someone is setting the size then they know exactly how big they wish the list to be, so why waste memory. It was just a simple rule you could always remember, setting size always implicitly sets capacity.
But I am not strongly attached to those semantics. If others chime in and wish to see the behavior changed, we can do it. But otherwise I think it best to leave alone.
+1 to proposal.
I kinda thought it was already like that.
This makes sense to me too, if I am understanding correctly. So long as list.size is being set to less than capacity, it should not alter capacity (since that is the purpose of trim).
+1 from my side.
I think it's better to manage capacity separate from the size.
+1 - I'm on board
Promoted to ticket #1607 and assigned to brian
Renamed from Thoughts about List size and capacity to Fix List.size to not automatically change capacity
Ticket resolved in 1.0.61
Change List.size to only change capacity if backing array needs to be grown.
Login or Signup to reply.