This isn’t a question specifically tied to rust, but instead in general:
If I have a piece of code like the following:
let fps = 1. / ( duration.as_secs() as f32 + ( duration.subsec_nanos() as f32 / 1_000_000_000.) );
but I decide to make this more efficient using some simple logic and algebra and I come out with this:
let fps = 1_000_000_000. / duration.as_nanos() as f32;
Would it be appropriate to add a comment with the prior code as an explanation, or would it be up to the reader to interpret it? In a sense I feel like the comment would be useful, but would clog up code if you don’t particularly care about small bits like this… Any opinions?
If you’re curious as to how I got to this follow through:
- The output of the addition is the same as the output of
duration.as_nanos() as f32 / 1_000_000_000.
- Since I’m dividing
1.by this result, algebra says that (if I remember correctly):
x/(a/b) = (x/1)/(a/b) = (x/1)*(b/a) = //substituting x for one 1*b/a = b/a
- a) and therefore we end up at the result