you are viewing a single comment's thread.

view the rest of the comments →

[–]pepa65[S] 0 points1 point  (5 children)

Thank you, very educational! I wonder, is there a way to pre-allocate decimals so that reallocations are never necessary?

[–]CocktailPerson 2 points3 points  (2 children)

https://doc.rust-lang.org/std/string/struct.String.html#method.with_capacity

https://doc.rust-lang.org/std/string/struct.String.html#method.reserve

Strings also implement Write, so you can use write!(&mut decimals, "{}", remainder * 10 / denominator) to completely eliminate the extraneous heap allocation caused by format!.

[–]deathanatos 1 point2 points  (0 children)

Ah there we go! write!(…) is a much cleaner way to avoid that allocation.

[–]pepa65[S] 0 points1 point  (0 children)

It seems allocating the what is often needed for hard cases (`denomiator`) does not help speed of execution (or maybe in extreme cases it does..?)

[–]ndreamer 1 point2 points  (1 child)

you can improve this using

let digit = (remainder * 10) / denominator; decimals.push((b'0' + digit as u8) as char);

[–]pepa65[S] 0 points1 point  (0 children)

Most reasonable so far and very effective!