Code comparison
Which one of the following two pieces of code should be 开发者_运维技巧preferred over other? and on what basis the decision should be taken generally?
MAX_LIMIT might vary from 1000 to 5000 in various calls of this function.
for (i=0;i<MAX_LIMIT;++i)
{
for (j=0;j<MAX_LIMIT;++j)
{
anObj.setMatrix(i,j,0);
}
}
for (i=0;i<MAX_LIMIT;++i)
{
anObj.setMatrix(i,i,1);
}
vs
for (i=0;i<MAX_LIMIT;++i)
{
for (j=0;j<MAX_LIMIT;++j)
{
if(i==j)
{
anObj.setMatrix(i,j,1);
}
else
{
anObj.setMatrix(i,j,0);
}
}
}
Thanks.
The perfomance of the two should be asymptoticaly equal, as both run in O(n^2). You should probably prefer the one with most readability.
The second, which does what it says. However, I'd strongly prefer
for (i=0;i<MAX_LIMIT;++i)
{
for (j=0;j<MAX_LIMIT;++j)
{
anObj.setMatrix(i, j, i==j ? 1 : 0);
}
}
In my opinion I would go with the second of the two. It is best to limit the number of times you have to loop through something. Since you're looking at at least O(n^2) runtime I would definately limity yourself to only 2 loops.
Better for what? I think the second version is easiest to understand at a glance, although other people may have other opinions.
If you're interested in performance, it should be easy to time the two methods. (It may even be relevant.)
Taking a look at this for performance, I'd suspect the second method would be faster, because it will work through the array one cache line at a time. The first method will work through the array one cache line at a time, and then go on to execute N cache faults. My guess is that this is more significant than putting an extra conditional in the loop.
So, if array initialization takes a significant amount of time compared to other operations, and this matters, time each one and see. If not, then go with the more readable version.
精彩评论