examples: Avoid dividing index to get x, y; calculate index from x, y

Division is more expensive than multiplication, and this doesn't seem to
be optimize away, so iterating over `(0..height)` and `(0..width)`
provides better performance.

It's good to have the example show the best way to write code using
softbuffer, and this helps when using examples as a benchmark. This will
also be needed if Softbuffer supports formats where `stride` isn't just
`width * pixel_size`, and needs alignment.
This commit is contained in:
Ian Douglas Scott 2023-04-11 12:20:48 -07:00
parent 6da649e8a1
commit edc5c76180
3 changed files with 24 additions and 23 deletions

View file

@ -42,14 +42,14 @@ fn main() {
.unwrap();
let mut buffer = surface.buffer_mut().unwrap();
for index in 0..(width * height) {
let y = index / width;
let x = index % width;
let red = x % 255;
let green = y % 255;
let blue = (x * y) % 255;
buffer[index as usize] = blue | (green << 8) | (red << 16);
for y in 0..height {
for x in 0..width {
let red = x % 255;
let green = y % 255;
let blue = (x * y) % 255;
let index = y as usize * width as usize + x as usize;
buffer[index] = blue | (green << 8) | (red << 16);
}
}
buffer.present().unwrap();