let's say I have the following loops:
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
if(tilesMap[i][j])
(tilesMap[i][j])->Draw(wind开发者_运维知识库ow) ;
}
}
and
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
(tilesMap[i][j])->Draw(window) ;
}
}
Is there any way I can make this "generic", ie if some boolean is true, I will call the first code segment, if not I'll call the second code segment. I obviously could do a test before the loop and branch on the right loop, but then I have to duplicate the loop "header" and the instruction inside too, and change it twice every time I change the code inside the loop. The other solution is to do a test inside the lopp at every iteration, but this would make way too many tests at runtime. Is there any other way I can do this? thanks
EDIT: this is just a question for my knowledge, I'm perfectly fine with duplicating my code for such small amount
You can use a pointer to a function(i,j).
Or an object. If you use C++, you can do it object oriented way i.e. with a virtual method and inheritance. It will need a lot of source lines, but it will be clean code. :-)
IMO, this code is small enough to just duplicate the loop. I'd be okay with a tiny bit of code-duplication if it makes it more readable and helps performance.
I would say that putting a test inside the loop could make it harder to read since it increases the nesting depth.
Branch predictors work quite well.
That said, you could wrap your two loop bodies in strategy objects, run the test outside of the loop once to choose one, and have the loop body delegate to the strategy method.
精彩评论