Indeed; I sometimes have to remind myself that extra variables don't mean that the program uses extra memory or extra cpu-cycles. The pawns-function above is one of my more extreme examples; it's basically a massive list of variables/definitions, one building on top of the previous, to calculate an end result. Then at the end of the function, another function is called. The let-statements even make it possible to omit an explicit if-statement, and match-statement.Joost Buijs wrote: ↑Tue Oct 06, 2020 5:15 pm In the past when compilers were not that smart a different programming style was needed to get good performance, basically you had to optimize the whole code flow by hand, fortunately this no longer necessary.
There's a great video on Youtube with regard to optimization by LLVM. (It's in a video about Rust, but it would be the same for Clang.) There, the speaker shows a function with quite a lot of variables, statements, and even branches, and then he starts to elide (omit) variables, by packing the stuff from the variable directly into the place where the variable is used. (Just like I did with the square-attacked function above.) After that, he continues with the branches and other statements. Eventually he comes to this conclusion:
Original:
Code: Select all
fn do_some_stuff (x : u8) -> u8 {
let mut result = 0
//
// lots of code here to calculate result
///
return result;
}
Code: Select all
fn do_some_stuff( x: u8 ) -> u8 {
return x + 10;
}
After a saw that video, I don't really think about using "extra" variables or higher-level language constructs. The compiler will remove all of them. The only thing to watch out for, is allocations. (Don't use a vector if an array will do; that sort of thing.)