|
|
|
|
|
by drmikeando
977 days ago
|
|
IMO the reason the compiler doesn't add special cases for the simplest version is that it doesn't know which of its _many_ special cases to use. If you actually use the unoptimised version of the code like void withSwitch(vector<int>& Values, bool v) {
if (v) {
multiply1(Values, 2.0);
} else {
multiply1(Values, 3.0);
}
}
Then it actually inlines the code and optimises each one correctly, as it has context about which special cases are available. (Doesn't even need the `inline` keyword for this at `-O2`)You can see the code here: https://godbolt.org/z/5beeYe77a |
|
My goal was to not rely on site-specific optimization and instead have one separately compiled function body that can be improved for common cases. Certainly, once the compiler has a full view of everything it can take advantage of information as it pleases but this is less controllable. If I were really picky about optimizing for each use I would make it a template.
>Doesn't even need the `inline` keyword for this at `-O2`
The inline keyword means little in terms of actually causing inlining to happen. I would expect the majority of inlining compilers do happens automatically on functions that lack the "inline" keyword. Conversely, programmers probably add "inline" as an incantation all over the place not knowing that compilers often ignore it.