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

@ -4,17 +4,17 @@ use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
fn redraw(buffer: &mut [u32], width: usize, height: usize, flag: bool) {
for (index, color) in buffer.iter_mut().enumerate() {
let y = index / width;
let x = index % width;
if flag && x >= 100 && x < width - 100 && y >= 100 && y < height - 100 {
*color = 0x00ffffff;
} else {
let red = (x & 0xff) ^ (y & 0xff);
let green = (x & 0x7f) ^ (y & 0x7f);
let blue = (x & 0x3f) ^ (y & 0x3f);
*color = (blue | (green << 8) | (red << 16)) as u32;
for y in 0..height {
for x in 0..width {
let value = if flag && x >= 100 && x < width - 100 && y >= 100 && y < height - 100 {
0x00ffffff
} else {
let red = (x & 0xff) ^ (y & 0xff);
let green = (x & 0x7f) ^ (y & 0x7f);
let blue = (x & 0x3f) ^ (y & 0x3f);
(blue | (green << 8) | (red << 16)) as u32
};
buffer[y * width + x] = value;
}
}
}