I think the implications here are all allocator related inherently. For instance, in the case that the resize call returns false, you can end up with 3 separate allocator functions called in this order…
- Resize
- Alloc
- Free
Ultimately the reason being is that it’s not abandonSlice
(not an existing function) which would be of trivial runtime. Since the array list tracks the length of the total allocation with the capacity
data member and only the used items with the items.len
, it cannot just return items because then you may have capacity - items.len
items unaccounted for.
You could try to cheat death here by just doing something like (pseudo code)…
// slice abandonment
var tmp_items = self.items;
tmp_items.len = self.capacity;
self.items = &[_]T{}; // reset
return tmp_items;
…and then you’d have the full capacity slice and the whole thing would be trivial runtime if that’s important and if exact item count doesn’t matter (which unfortunately often does).
2 Likes
I think I see what you’re getting at. Well the main thing I was using toOwnedSlice() for previously was to concatenate a secondary ArrayList to a primary one when doing multi-line input on the console. So if you read a single line you just read into the main array list, but when you go to read multiple lines you would read each of those lines into a separate ArrayList and append it to the primary list at the same time with toOwnedSlice. I have since erased that code and confined the program to only read a single line. Though I plan to go back and reimplement it later. But yeah now that you mention it abandonSlice might be more appropriate here, since I am looking to minimize the overhead as much as possible. Unfortunately I cannot find abandonSlice anywhere in the standard library
, but I will keep your pseudo code example you gave and try it out later the first chance I get.
Yeah, I just made that one up lol. Sounds good - if you want to follow up on this, let’s take that to a private message or open a new thread to keep this one on topic 