Re: [Dev-C++] a trivial question on for loops
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Jason H. <jas...@bt...> - 2001-10-17 03:56:31
|
It would depend upon implementation, but I don't think getting the end through the function is likely to be much slower than using a temporary local store as a comparison. The idea is right, but it is more than likely that in compiler optimisation that the call to l_int.end() would be inlined, and take very little code. If end is of constant value it may even be possible that the compiler would account for it, although I couldn't be sure. The call to end would likely be just a return of a reference stored in the container object, possibly a constant reference. The only time it would be of any significance would be if you were creating time critical code, and in that case it would be best to avoid using a list. Also if the list was changed within the for loop then it's possible that the stop value would become invalid, although that would be less likely in a list than in other containers. After saying all that I would agree that in theory the second version would be very slightly more efficient, but on the other hand it involves more code, creates an extra variable (iterator), which takes up some amount of memory. It may even be that the creation of the const_iterator takes more time than you gain in the for loop, although that is probably unlikely. As usualy I've gone overkill in this reply, oops - sorry! Jason. ----- Original Message ----- From: "Luigi Santillo" <gi...@li...> To: <dev...@li...> Sent: Tuesday, October 16, 2001 6:40 PM Subject: [Dev-C++] a trivial question on for loops > Hello everybody, > > I know this is an easy one, but what I've seen on a C++ book puzzled me. > > Consider the two pieces of code that follow: > > 1) as found on a recent C++ book > list<int> l_int; > // ... fill the list with a few intergers > for (list<int>::const_iterator i = l_int.begin(), i != l_int.end(); ++i) > // ... do something > > 2) as I used to know > list<int> l_int; > // ... fill the list with a few intergers > list<int>::const_iterator stop = l_int.end(); > for (list<int>::const_iterator i = l_int.begin(), i != stop; ++i) > // ... do something > > The two pieces are equivalent, but the second one is more efficient. Do you > agree with me? > > -- > gisan > gi...@li... > > > _______________________________________________ > Dev-cpp-users mailing list > Dev...@li... > https://lists.sourceforge.net/lists/listinfo/dev-cpp-users |