Implementing arrays in go

https://play.golang.org/p/Tgn3xGiHOIb
Im trying to implement an array here, but it seems some of the methods arent efficient because of things like memory allocations.
Can someone pin point places that can be improved to make the code more efficient? for example where there aint no need to return a new array.

Every copy and append can lead to allocations. I wrote about it on my blog: https://developer20.com/what-you-should-know-about-go-slices/

So, for example splice can allocate as well as unshift. To limit those allocations, you can create the array with the final capacity (if you know it at the very beginning).

1 Like

Hey,

Thanks for an awesome blog post. I wanted to clarify some few things. Since append and copy allocate memory when the capacity is exceeded, you suggest to make an array whose location in memory will remain constant right?(that is no need for future memory allocations), and in which all operations like delete, splice and unshift will be done on

Sorry if my question sounds weird. Im still getting a hang of CS.

the copy will always allocate because it copies bites from one array to another. Preallocating the slice will help reducing memory allocations done by append() only.

Ahh i see. So in my example, i can allocate a slice maybe with a capacity of 10, and basically work with it. i.e assigning the returned data and so on