@safe and null dereferencing

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 27 10:43:17 PDT 2017


On Thu, Jul 27, 2017 at 05:33:22PM +0000, Adrian Matoga via Digitalmars-d wrote:
[...]
> Why can't we just make the compiler insert null checks in @safe code?

Because not inserting null checks is a sacred cow we inherited from the
C/C++ days of POOP (premature optimization oriented programming), and we
are loathe to slaughter it.  :-P  We should seriously take some
measurements of this in a large D project to determine whether or not
inserting null checks actually makes a significant difference in
performance.


> We can afford bounds checking even in @system -O -release. C++ can
> afford null check upon executing an std::function. The pointer would
> most likely be in a register anyway, and the conditional branch would
> almost always not be taken, so the cost of that check would be barely
> measurable. Moreover, the compiler can elide the check e.g. if the
> access via pointer is made in a loop in which the pointer doesn't
> change. And if you prove that this tiny little check ruins performance
> of your code, there's @trusted to help you.

The compiler can (and should, if it doesn't already) also propagate
non-nullness (ala VRP) as part of its dataflow analysis, so that once a
pointer has been established to be non-null, all subsequent checks of
that pointer can be elided (until the next assignment to the pointer, of
course).


T

-- 
Public parking: euphemism for paid parking. -- Flora


More information about the Digitalmars-d mailing list