Passing array as const slows down code?

Jonathan M Davis jmdavisProg at gmx.com
Fri Apr 27 17:04:24 PDT 2012


On Saturday, April 28, 2012 01:26:38 Era Scarecrow wrote:
> On Friday, 27 April 2012 at 22:40:46 UTC, H. S. Teoh wrote:
> > I recommend the opposite, actually. Most D code by default
> > should be @safe (don't know about nothrow though). It's good to
> > mark most things as @safe and pure, and let the compiler catch
> > careless mistakes.
> 
> Your probably right..
> 
> > Dynamic arrays are always passed by reference (i.e. fat
> > pointer). AFAIK
> > the compiler does not change this just because of certain tags
> > on the function.
> 
> That's why i wasn't sure... I was pretty sure it was passed via
> fat pointer but if adding @safe and pure makes it slower,
> something else is going on. Perhaps just a ton more checks to
> make sure it doesn't during debug mode?

pure and @safe have _zero_ affect on the types of function parameters or how 
they're passed. They allow the compiler to provide additional compile-time 
checks. The _only_ case that I'm aware of where @safe affects code generation 
is that array bounds checking is not removed in @safe code with -release like 
it is in @system and @trusted code (-noboundscheck will remove it in all 
code). pure can affect code optimizations in _calling_ code (e.g. making it so 
that a strongly pure function is only called once in an expression when it's 
called multiple times with the same arguments within that expression), but it 
doesn't affect the function's code generation at all.

_Nothing_ affects how arrays are passed beyond ref, out, and in. The type of an 
array doesn't change due to attributes on the function that it's a parameter 
for. Arrays are literally structs that looks something like

struct DynamicArray(T)
{
 T* ptr;
 size_t length;
}

and their semantics for being passed to a function are identical to what you'd 
expect from any struct with such a definition.

http://dlang.org/d-array-article.html

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list