Currently I’m writing byte-by-byte to a slice by a loop. The slice contains image pixels:
<code>func (r *Painter) Paint() {
for i := 0; i < len(r.Image.Pix); i += 1 {
// Write a single byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i] |= 0x44
case 1:
r.Image.Pix[i] |= 0x88
case 2:
r.Image.Pix[i] |= 0xcc
}
}
}
</code>
<code>func (r *Painter) Paint() {
for i := 0; i < len(r.Image.Pix); i += 1 {
// Write a single byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i] |= 0x44
case 1:
r.Image.Pix[i] |= 0x88
case 2:
r.Image.Pix[i] |= 0xcc
}
}
}
</code>
func (r *Painter) Paint() {
for i := 0; i < len(r.Image.Pix); i += 1 {
// Write a single byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i] |= 0x44
case 1:
r.Image.Pix[i] |= 0x88
case 2:
r.Image.Pix[i] |= 0xcc
}
}
}
For writing to hard disk, we have tested before that writing in batches with specific sizes would be optimal. But here we are writing to memory and I’m not sure if writing in batches would be more efficient or not.
Is writing in batches more efficient? For example, inside each loop iteration, we write 3 bytes like below. If writing in batches of multiple bytes is more efficient, what’s the optimal amount of bytes to write by each iteration?
<code> // ...
for i := 0; i < len(r.Image.Pix); i += 3 {
// Write 1st byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i] |= 0x44
case 1:
r.Image.Pix[i] |= 0x88
case 2:
r.Image.Pix[i] |= 0xcc
}
// Write 2nd byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i+1] |= 0x44
case 1:
r.Image.Pix[i+1] |= 0x88
case 2:
r.Image.Pix[i+1] |= 0xcc
}
// Write 3rd byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i+2] |= 0x44
case 1:
r.Image.Pix[i+2] |= 0x88
case 2:
r.Image.Pix[i+2] |= 0xcc
}
}
// ...
</code>
<code> // ...
for i := 0; i < len(r.Image.Pix); i += 3 {
// Write 1st byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i] |= 0x44
case 1:
r.Image.Pix[i] |= 0x88
case 2:
r.Image.Pix[i] |= 0xcc
}
// Write 2nd byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i+1] |= 0x44
case 1:
r.Image.Pix[i+1] |= 0x88
case 2:
r.Image.Pix[i+1] |= 0xcc
}
// Write 3rd byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i+2] |= 0x44
case 1:
r.Image.Pix[i+2] |= 0x88
case 2:
r.Image.Pix[i+2] |= 0xcc
}
}
// ...
</code>
// ...
for i := 0; i < len(r.Image.Pix); i += 3 {
// Write 1st byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i] |= 0x44
case 1:
r.Image.Pix[i] |= 0x88
case 2:
r.Image.Pix[i] |= 0xcc
}
// Write 2nd byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i+1] |= 0x44
case 1:
r.Image.Pix[i+1] |= 0x88
case 2:
r.Image.Pix[i+1] |= 0xcc
}
// Write 3rd byte to pixel array
switch ForkInTheRoad {
case 0:
r.Image.Pix[i+2] |= 0x44
case 1:
r.Image.Pix[i+2] |= 0x88
case 2:
r.Image.Pix[i+2] |= 0xcc
}
}
// ...