请简述以下两个for 循环的优缺点

今天笔试时候遇到一个问题,找到相似的。

for (i=0; i<N; i++)
{
    if (condition)
        DoSomething();
    else
        DoOtherthing();
}
if (condition) { for (i=0; i<N; i++) DoSomething(); } else { for (i=0; i<N; i++) DoOtherthing(); }

优点:程序简洁

缺点:多执行了N-1次逻辑判断,并且打断了循环“流水线”作业,使得编译器不能对循环进行优化处理,降低了效率。

优点:循环的效率高

缺点:程序不简洁

猜你喜欢

转载自www.cnblogs.com/jason-linux/p/10603471.html