std.string.translate using initializing twice?

Jonathan M Davis jmdavisprog at gmail.com
Mon Aug 9 18:23:55 PDT 2010


On Monday, August 09, 2010 18:03:48 simendsjo wrote:
> Yeah. Don't remember when, don't remember where, but I too have read
> that preincrement is faster (PS: I don't know any assembler!).
> 
> As long as I don't use it in an expression, I always use post-increment
> as it shouldn't make a difference.

post-increment creates a temporary. It's really doing something like

T temp = i;
++i;
//use temp in the expression with i++

The temporary is useless and pointless if i++ is by itself rather than in an 
expression. In the case of primitives, the compiler knows enough to optimize out 
the temporary, but in the case of operator overloading in C++, because pre and 
post-increment are overloaded separately, it can't know for sure that it's safe 
to do the optimization, so it doesn't do it, and your code is less efficient. 
That's why code like

for(vector<int>::iterator iter = vec.begin(),
                                       end  = vec.end();
      iter != end;
      iter++)
{
  ...
}

is so bad. You really need to use ++iter in that case. However, in D, this isn't 
a problem because pre-increment and post-increment are overloaded by one 
function and the compiler takes care of whether it should be pre or post when 
it's used. So, it should be able to do the optimization just fine. But I've 
programmed in C++ for so long (where it does matter), that I instinctively react 
negatively to post-increment where a pre-increment will do even in languages 
like Java (which doesn't have operator overloading) or D where it doesn't 
matter.

I'd argue, that everyone (at least everyone programming in C++) should just be 
in the habit of using pre-increment except the cases where a post-increment is 
necessary (then you never have to worry about whether it's less efficient to use 
post-increment in a particular case), but for whatever reason, new programmers 
are pretty much always taught post-increment first, and so that's what most 
programmers are used to using.

In reality, it's becoming less relevant as newer languages are designed in a 
manner than there is no difference in efficiency, but my natural reaction is still 
very much that post-increment by itself is evil.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list