Passing array as const slows down code?

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Fri Apr 27 09:37:41 PDT 2012


On 27/04/12 18:02, 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.

Yes, me too, hence confusion.

I have to say I'm somewhat confused about whether the pure markings are really 
accurate.  The reputation() modifies the reputationUser_ and reputationObject_ 
internal arrays and hence the returned values of reputationUser() and 
reputationObject().  It's true that for a given input to reputation(), the 
outcome will always be the same, but there's nevertheless mutability involved: 
if I pass one input to reputation(), and then another, the reputationObject() 
and ...User() outputs will change as a result.

I suppose it's a kind of weak purity, but I'm not too happy with it.  I suppose 
I could get reputation() to _return_ reputationObject and reputationUser instead 
of having them called via functions; but I'd be worried it would slow everything 
down substantially.

Background to this piece of code: it's a D rewrite of some C++ I wrote a couple 
of years back as part of a research project.  I took quite a lot of time to make 
the C++ as efficient as possible, so this is a nice test case to see if I can 
get D to produce similar efficiency while having much more elegantly-written 
code.  It's also just a nice way to learn to be "D-ish", working on a problem 
that I already understand well.

Currently the D code is MUCH more elegant and easy to read than the C++, and 
runs about 2 seconds slower for the test case implemented here (so on my 
machine, C++ does it in about 21s as opposed to D's 23), with that difference 
scaling with problem size.  It's a tolerable difference, though it would be nice 
to see if I can close the gap.


More information about the Digitalmars-d-learn mailing list