Passing array as const slows down code?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Apr 27 15:41:45 PDT 2012


On Sat, Apr 28, 2012 at 12:29:24AM +0200, Era Scarecrow wrote:
> On Friday, 27 April 2012 at 16:02:00 UTC, Steven Schveighoffer
> wrote:
[...]
> >Hm.. you have marked all your functions pure as well.  I don't think
> >this will affect anything in the current implementation, but it
> >might.  However, I'd expect the opposite (const version is faster) if
> >anything.
> 
> 
>  Perhaps I'm wrong, but seeing as your working with a struct I would
>  think the following should be noted.
> 
>  First, pure and nothrow. Nothing wrong with labeling functions as
>  such, but I would recommend removing them and once the whole thing is
>  done and you get it in a finished state that you start adding them
>  back in if you think they qualify. Recently I know I added a @safe
>  token to a simple function which of course threw a range exception
>  later. Oddly enough it was because I didn't check if the array was
>  null before accessing it.

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.


>  Second, you are passing an array of structs. Either a fat pointer is
>  being passed, or it's shallow copying; depending on the scenario
>  either could be true. As an array it should be passing a fat pointer
>  but if the compiler has to make certain guarantees based on your tags
>  it may not. Depending on the size of the array, I would think this
>  might be the case.

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.


> Actually I _think_ it would in this case. Imagine a pure function that
> gives different results from the input when the input changes during
> execution. By making a local copy the input can't be changed from the
> outside and thereby returns that guarantee.
[...]

No, that's wrong. The compiler checks the code at runtime to prevent
impure code from slipping into the binary. It does not do anything to
"patch over" impure code to make it pure.


T

-- 
Why are you blatanly misspelling "blatant"? -- Branden Robinson


More information about the Digitalmars-d-learn mailing list