#Why dont i need to free a owned slice?

1 messages · Page 1 of 1 (latest)

strong prism
#

it doesnt have a deint because its just a simple slice not a container. you still need to free it because its still allocated just like the items of an arraylist are it simply transfers ownership out of the arraylist (metaphorically speaking, zig has no concept of ownership)

#

you just free it with allocator.free(tokens)

neat pond
#

arraylist if it's expected that the caller might need to add or remove items, slice if not

topaz plinth
#

the function that returns a slice often takes in an allocator, which in most cases indicates that the slice was allocated and needs to be deinit after done using it

sand pebble
#

Worth noting that toOwnedSlice might allocate a new buffer and copy elements over. For that reason, if you are looking for absolute best performance it might be better to return the array directly.
Would be nice if we had a DynamicBoundedArray to return instead.

neat pond
#

how would such a thing work?

vocal sparrow
sand pebble
sand pebble
vocal sparrow
#

im aware

#

but u said return the array, which sounds to me like u means list.items

#

which, ig its allocated, so that could be fine

sand pebble
#

Oh no I meant the array list

vocal sparrow
#

but i think deinit does stuff besides freeing the items

#

oh

#

gotcha

sand pebble
#

So you need to return a type that stores a slice + the size of the allocation so it can be freed

vocal sparrow
#

right that makes sense

#

i couldnt remember

#

not at my computer rn to check the impl

sand pebble
#

Yeah array list is a bit weird in it's impl but it let's you query items.len or iterate over items that way

vocal sparrow
#

yeah

neat pond
sand pebble
#

No you are right, it's no different

neat pond
#

as long as you free the returned slice (and free memory owned by each item, if there is any) you're fine

#

toOwnedSlice leaves the arraylist empty, so calling deinit is safe but unnecessary

sand pebble
#

ToOwnedSlice may allocate and copy, so yeah it's not free.