1st implementation
I have this function. The input is a slice of uint8
bytes. This function inserts a new byte equal to 255
or 0xff
value after each 3
bytes.
func ApplyAlpha(pix []uint8) []uint8 {
l := 0
for i := 0; i < len(pix); i++ {
l++
if l%3 == 0 && i+1 < len(pix) {
// Insert alpha at the current position
pix = append(pix[:i+1], append([]byte{255}, pix[i+1:]...)...)
i++
}
}
return pix
}
2nd implementation
Optimized?
To optimized the function, I can rewrite it like this:
func ApplyAlpha(pix []uint8) []uint8 {
newPix := make([]uint8, len(pix)/3*4, len(pix)/3*4)
l := 0
for i := 0; i < len(pix); i++ {
newPix[l] = pix[i]
l++
if (i+1)%3 == 0 {
// Insert alpha at the current position
newPix[l] = 255
l++
}
}
pix = newPix
return pix
}
Problem
Both the 1st implementation and the 2nd one have draw backs:
- 1st implementation is expensive due to
append
calls. - 2nd implementation is consuming lots of memory due to declaring a totally new slice.
Question
Is there any trick or workaround of which I’m not aware? To optimize the implementation even further?