[prev in list] [next in list] [prev in thread] [next in thread]
List: kde-core-devel
Subject: Re: Krazy: prefix vs. postfix ++ and -- operators
From: Matthew Dawson <matthew () mjdsystems ! ca>
Date: 2011-01-11 15:44:28
Message-ID: 201101111044.38606.matthew () mjdsystems ! ca
[Download RAW message or body]
On Tuesday 11 January 2011 10:16:23 Christoph Feck wrote:
> Krazy says:
>
> "You should use ++ and -- as prefix whenever possible as these are more
> efficient than postfix operators. Prefix increments first and then uses the
> variable, postfix uses the actual; the variable is incremented as well.
> Because of this, the prefix operators are inherently more efficient."
>
> Considering that today's CPUs have multiple pipelines, using a value directly
> seems faster to me than waiting for it to be incremented or decremented.
>
> Is this krazy warning still correct?
>
> Christoph Feck (kdepepo)
>
(This all applies equally to the -- operator, it is omitted for clarity.)
I'm assuming this Krazy warning is for incrementing a variable in a for loop as \
opposed to incrementing and assigning the variable. Prefix is generally considered \
faster as it avoids an unnecessary copy of the data. Effectively, the prefix \
increment operator looks like: int &operator++(){ //Prefix
number = number+1;
return number;
}
Verus postfix looks like:
int operator++(int){
int temp = number;
number = number+1;
return temp;
}
When executing a for loop, using the postfix operator incurs that copy and thus can \
slow down the code. This would be especially more relevant with iterators or the \
like as the compiler would have a harder time optimizing out the copy.
However when using the ++ operator in assignment, like:
int num2 = num1++;
int num3 = ++num1;
Both lines will have different results in num2 and num3 (num2 != num3) and the \
appropriate operator should be used. So postfix doesn't use the value directly. In \
fact the prefix uses the value directly.
Matthew
["signature.asc" (application/pgp-signature)]
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic