Given:
- slice with pre-known capacity
- capacity and number of slices are large , and around 15MB of memory will be used, so I don't want to waste memory and want to keep minimum memory.
- slice will be updated by removing first element and adding new element to end of slice.
b = append(b[1:], n)
will increase capacity
to shift and assign myself, I wrote
func shiftAndPut(a []int, n int) (b []int) {
b = make([]int, cap(a), cap(a))
for i,v := range(a[1:]) {
b[i] = v
}
b[len(b)-1] = n
return
}
https://play.golang.org/p/7xIBh0UPp2w
It keeps the capacity same, but requires various computations
- iterating slice one time,
- calling of function,
- new variable for small time,
- sub slicing in range function, which adds more computations,
- etc
Is there any more optimised way to do this?