Performance of default and enum parameters
jmh530
john.michael.hall at gmail.com
Wed Feb 7 23:04:29 UTC 2018
I'm a little curious on the impact of default and enum parameters
on performance.
In the simple example below, I have foo and bar that return
different results depending on a bool. Foo is a template with
check as a template parameter and bar is a normal function. foo
creates two different versions so it never needs to perform a
run-time evaluation of check.
However, I was a little curious about bar. Obviously if check is
passed as either true or false, then the if statement has to be
run, but I wasn't sure what happens if check is not passed or if
check is known at compile-time.
If check is not passed, I think it depends on how default
function arguments work. I could imagine that it works in two
ways: 1) if you call bar(x), then the compiler effectively
re-writes it to bar(x, true), which would mean that the if
statement must run, 2) the compiler creates functions int bar(int
x) and int bar(int x, bool check), where the first has the check
optimized away and the second is as normal, calling bar(x) means
that the optimized one is called.
If check is known at compile-time, I would think that the
compiler could optimize away the if statement because it is known
at compile-time which part will be there or not.
int foo(bool check = true)(int x)
{
static if (check)
return x;
else
return x + 1;
}
int bar(int x, bool check = true)
{
if (check)
return x;
else
return x + 1;
}
enum bool val = false;
void main()
{
import std.stdio : writeln;
int x = 1;
writeln(foo(x)); //two versions of foo
writeln(foo!false(x)); //two versions of foo
writeln(bar(x)); //does run-time if happen?
writeln(bar(x, true)); //if statement at run-time
writeln(bar(x, false)); //if statement at run-time
writeln(foo!val(x)); //same as foo!false
writeln(bar(x, val)); //does run-time if happen?
}
More information about the Digitalmars-d-learn
mailing list