Making preconditions better specified and faster

qznc via Digitalmars-d digitalmars-d at puremagic.com
Fri Dec 16 02:28:03 PST 2016


On Thursday, 15 December 2016 at 18:48:22 UTC, Andrei 
Alexandrescu wrote:
> https://issues.dlang.org/show_bug.cgi?id=16975

Whenever I think about preconditions and speed, I think that they 
should actually be put into the caller instead of into the 
function/callee. The chance that intra-procedural optimization 
can remove the checks increases. Of course, inlining voids the 
discussion, but think about the non-inline case.

pragma(inline, false)
int twice(int x)
   in { assert(x < int.max / 2); }
   body { return x + x; }

void main() {
   int x = 42;
   int y = twice(x);
}

You can put the check at the front of twice, which makes it 
necessary to evaluate the check at runtime. Alternatively, put 
the check into the main function, where constant propagation and 
folding can easily remove the check.

Obviously, the downside is code size when precondition-functions 
are called from more than one point.

(This is probably off-topic for the issue, thus my comment here)


More information about the Digitalmars-d mailing list