-
April 12th, 2010, 12:48 PM
#1
Is there any danger in doing this?
I just changed job and my new company has a lot of code like this:
Code:
for(foo::iterator it = foobar.begin(); it != foobar.end(); ++it)
I always did it this way:
Code:
for(foo::iterator it = foobar.begin(), it_end = foobar.end(); it != it_end; ++it)
(Indirectly through a foreach macro of course)
The latter is quiet a bit faster. The only reason I can think of to do the former is if the loop changes what's in the container. Is there something I'm missing?
-
April 12th, 2010, 12:54 PM
#2
Re: Is there any danger in doing this?
Your method is typically better, but as you say in specific cases it is not appropriate.
-
April 12th, 2010, 03:18 PM
#3
Re: Is there any danger in doing this?
Perhaps they thought the call to the end function would be optimized and so it wouldn't make a difference. Did you look at the assembly code to confirm? Perhaps you should point it out to them if your way results in significant run time improvement. I'm not sure what you mean by "quite a bit faster". You could profile two functions, analyze the difference, and then use the data to convince your new teammates that there is a better way. I looked at the assembly code for a small project and as you point out there is less code executing as the body of the for loop doing it your way. This is one of the reasons for item 43 of "Effective STL" by Scott Meyers.
Last edited by kempofighter; April 12th, 2010 at 03:36 PM.
Reason: Added book reference.
-
April 12th, 2010, 03:41 PM
#4
Re: Is there any danger in doing this?
I didn't look at the assembly, but the loop itself in 3x faster if calling end over and over again is not done. I don't think the compiler is smart enough to optimize that out, as end() is a function and it's not const.
-
April 12th, 2010, 05:50 PM
#5
Re: Is there any danger in doing this?
Originally Posted by ninja9578
I didn't look at the assembly, but the loop itself in 3x faster if calling end over and over again is not done. I don't think the compiler is smart enough to optimize that out, as end() is a function and it's not const.
I still would have expected to be inlined though...
-
April 14th, 2010, 08:04 AM
#6
Re: Is there any danger in doing this?
it might be quite revealing for you to raise the issue. if your method is just as reliable but typically faster then suggest the standard be changed. no reason to assume that just because it is in place it has been communicated by god. it might give you an inidcation of what type od corporate environment you've signed onto.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|