zoukankan      html  css  js  c++  java
  • 关于先判断再循环和先循环再判断的浅见

    今天项目中碰到了这个问题,在网络上试图找了一下别人的见解,然后得出自己的浅见。

    引用:

    http://blog.sina.com.cn/s/blog_9342cd570102v3pr.html

    https://segmentfault.com/q/1010000005710307/a-1020000005710886

    ------------------------------------------------------------------------------------------------------------------------

    根据以上得知:

    1 简短的代码段,先判断再循环和先循环再判断执行一千万次的执行效率相差无几

    2 先判断再循环的代码维护不便并且代码冗余

    --------------------------------------------以下为代码段和个人浅见--------------------------------------------

    先判断再循环:

     1 if(type==1){
     2     for (var i = 0; i < item.length; i++) {
     3         console.log(item[i].Aa)
     4     }
     5 }else if(type==2){
     6     for (var i = 0; i < item.length; i++) {
     7         console.log(item[i].Bb)
     8     }
     9 }else if(type==3){
    10     for (var i = 0; i < item.length; i++) {
    11         console.log(item[i].Cc)
    12     }
    13 }    

    先循环再判断:

    1 for (var i = 0; i < item.length; i++) {
    2     if(type==1){
    3         console.log(item[i].Aa)
    4     }else if(type==2){
    5         console.log(item[i].Bb)
    6     }else if(type==3){
    7         console.log(item[i].Cc)
    8     }
    9 }

    前者代码冗余且维护不便,而后者代码简洁方便维护,在执行效率相差无几的情况下,推荐使用后者

  • 相关阅读:
    inf的设置【知识】
    输入加速【模板】
    floyed算法【最短路】【模板】
    vector的erase函数使用
    欧拉图
    组合索引
    索引的存储
    索引失效
    装饰器和代理模式
    单例模式
  • 原文地址:https://www.cnblogs.com/marisen/p/10119959.html
Copyright © 2011-2022 走看看