Passing array as const slows down code?

Era Scarecrow rtcvb32 at yahoo.com
Fri Apr 27 15:29:24 PDT 2012


On Friday, 27 April 2012 at 16:02:00 UTC, Steven Schveighoffer 
wrote:
> On Fri, 27 Apr 2012 11:33:39 -0400, Joseph Rushton Wakeling
>> On 27/04/12 17:18, Steven Schveighoffer wrote:

>>> const should not affect code generation *at all*, except for 
>>> name mangling
>>> (const MyStruct is a different type from MyStruct), and 
>>> generating an extra
>>> TypeInfo for const MyStruct and const MyStruct[]. Const is 
>>> purely a compile-time
>>> concept.
>>>
>>> This cannot account for an extra 2 seconds. Something else is 
>>> happening.

>> The code is here: https://github.com/WebDrake/Dregs/
>>
>> You'll see that there are about 8 different functions in there 
>> which receive as input an array of type Rating!(UserID, 
>> ObjectID, Reputation)[].  These were the inputs I was marking 
>> as const.
>
> 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.

  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.

  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.

  Last try adding ref after const; At the off chance it's shallow 
copying, this should remove that.


More information about the Digitalmars-d-learn mailing list