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

@ -78,10 +78,11 @@ fn pre_render_frames(width: usize, height: usize) -> Vec<Vec<u32>> {
let render = |frame_id| {
let elapsed = ((frame_id as f64) / (60.0)) * 2.0 * PI;
(0..(width * height))
.map(|index| {
let y = ((index / width) as f64) / (height as f64);
let x = ((index % width) as f64) / (width as f64);
let coords = (0..height).flat_map(|x| (0..width).map(move |y| (x, y)));
coords
.map(|(x, y)| {
let y = (y as f64) / (height as f64);
let x = (x as f64) / (width as f64);
let red =
((((y + elapsed).sin() * 0.5 + 0.5) * 255.0).round() as u32).clamp(0, 255);
let green =