Re: faster?
Re: faster?
- Subject: Re: faster?
- From: Andreas Grosam <email@hidden>
- Date: Sat, 04 Feb 2012 10:56:23 +0100
On Feb 3, 2012, at 4:20 PM, Sean McBride wrote:
> On Fri, 3 Feb 2012 12:45:11 +0100, Andreas Grosam said:
>
>>> In my C++ code I'm using the libc++ library and my question is about
>> which construct is faster:
>>>
>>> for(auto line : lines)
>>> {
>>> ...
>>> }
>>>
>>> or
>>>
>>> for(auto it = lines.begin(); it != lines.end(); it++)
>>> {
>>> …
>>> }
>>
>> The auto keyword reduces verbosity only - and makes the code more
>> generic. A compiler should not generate different code - provided the
>> containers 'lines' are of the same type.
>
> Not so sure about that. Consider the points raised here:
>
> <http://llvm.org/docs/CodingStandards.html#ll_end>
> <http://llvm.org/docs/CodingStandards.html#micro_preincrement>
Whether ++i vs i++ is faster depends on how good the compiler is at optimizing. If i's type is non-trivial (e.g. not a integer or address) there should be really no difference. Unused temporaries whose ctor and dtor don't have side effects can be completely optimized away. So, ++i vs i++ will likely generate the same code in the majority of cases.
Likewise, whether
for (...; i != c.end(); …)
is slower than using a precomputed variable also depends how costly it is to access end(). As for STL containers, i != c.end() will most likely be a comparison of pointers - that is a very cheap operation. If the body of the loop happens to access the end pointer, it may be the case that the end pointer is already in a register. In this case, the version
for (...; i != c.end(); …)
might even be *faster* than using a precomputed variable.
Of course, there are a view requirements so that the compiler can optimize very well, e.g. the code must be visible to the translation unit (inlined) and the compiler applies inter-procedural optimizations.
Andreas
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
References: | |
| >faster? (From: Luca Ciciriello <email@hidden>) |
| >Re: faster? (From: Andreas Grosam <email@hidden>) |
| >Re: faster? (From: Sean McBride <email@hidden>) |