#1607 Fix List.size to not automatically change capacity

dsav Mon 8 Aug 2011

Recently I needed to write a code, which fills a list, but sometimes removes some elements from its end. I.e. the following workflow:

  1. Adding elements to the list. Sometimes remembering the list's size.
  2. If something goes wrong, rollback to the last remembered size, i.e. remove all elements from the end of the list, which are added after we saved that size. Continue step 1.

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:

list.removeRange(savedSize..<list.size)

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.

brian Mon 8 Aug 2011

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.

DanielFath Mon 8 Aug 2011

+1 to proposal.

I kinda thought it was already like that.

kevinpeno Mon 8 Aug 2011

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).

Yuri Strot Tue 9 Aug 2011

+1 from my side.

I think it's better to manage capacity separate from the size.

andy Tue 9 Aug 2011

+1 - I'm on board

brian Mon 14 Nov 2011

Promoted to ticket #1607 and assigned to brian

brian Mon 14 Nov 2011

Renamed from Thoughts about List size and capacity to Fix List.size to not automatically change capacity

brian Mon 14 Nov 2011

Ticket resolved in 1.0.61

Change List.size to only change capacity if backing array needs to be grown.

changeset

Login or Signup to reply.