So why doesn't popFront return an element?
Jonathan M Davis
jmdavisProg at gmx.com
Wed Apr 13 17:58:39 PDT 2011
> Oh, I thought the compiler could optimize calls to popFront if I'm not
> assigning its value.
>
> Doesn't a technique exist where if a function is called and I'm not
> assigning its result anywhere it should simply exit the function
> without returning anything? It seems like a valuable compiler
> optimization, if that is even possible.
That would depend on the type. For anything other than structs, if the
function is inlined, it should be able to do that (if it's not inlined, it
can't, because the returning is done inside of the function call). For
structs, it can probably do that if there's no postblit constructor and none
of its member variables have postblit constructors (or have member variables
of their own which have postblit constructors, etc.). If there's a postblit
constructor, however, it would have to be pure, otherwise it could have side
effects, and not doing the return could then alter the behavior of the
program. However, if it's pure, it probably can. I don't know what the
compiler does exactly.
Regardless, in the general case, the return value can't be optimized out,
because that's done in the function call, not at the call site. Inlined
functions should be able to get the optimization as long as it doesn't change
the behavior of the program to do so, which could require that the postblit
constructor is pure if a struct is being returned, and if you're returning an
expression, then that expression is still going to have to be evaluated unless
the compiler can determine that it has no side effects, which again, could
require any functions involved to be pure.
So, don't bet on such an optimization happening. dmd might manage it in some
cases, but in the most obvious cases, the cost of the return is pretty low
anyway (since it's either a primitive type or a reference).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list