欢迎光临
我们一直在努力

PB代码优化-数据库专栏,其他相关

建站超值云服务器,限时71元/月

pb代码优化
现今计算机的运行速度已经很快了,并且由于老板时常在耳边念着紧箍咒,因此,我们有意或者无意的忘记优化我们的代码,只要能完成任务就行了(我也是)。不过,我们闲下来的时候,不妨也来看看我们的代码是否有需要改进的地方。下面就是我觉得值得优化的几种情况。
第一种情况:
if condition1 and condition2 then

      //code goes here.

end if

if condition1 then

      if condition2 then

             //code goes here.

      end if

end if

 

对于书写的第一种方式,由于pb编译方式与常见的方式不同,就是无论条件1的值如何,都要对条件2进行运算。这样一来,当条件1为false时,就可能要无谓的对条件2进行运算了。就按随机的概率而言,可能会多进行一半的运算。因此,对于大多数情况而言,我想最好是以第二种方式书写。当然,特殊情况也是有的,那就是你的确想对条件2进行运算。类似地,对于or也一样。

 

if condition1 or condition2 then

      //code goes here.

end if

if condition1 then

      //code goes here.

else

      if condition2 then

             //code goes here.

      end if

end if
第二种情况:
if not condition then

      //code goes here.

end if

if condition then

      //no code goes here.

else

      //code goes here.

end if

 

对于上一种方式,条件表达式返回false并且再进行一个非运算,才执行下面的代码。这样相对于下面一种书写方式可能多执行了一个非运算。如果大家有什么疑问,您不妨测试一下下面这个例子:

 

//小测试:其中的判断条件只是为了表示一下,实际情况可能更复杂。

 

long i                   //计数器

long ll_start          //执行开始时间

long ll_used1       //方式一耗时

long ll_used2       //方式二耗时

 

//方式一

ll_start = cpu()

for i = 1 to 900000

      if not (1 > 1) then

             i = i

      end if

next        

ll_used1 = cpu() – ll_start

 

//方式二

ll_start = cpu()

for i = 1 to 900000

      if 1 > 1 then

            

      else

             i = i

      end if

next

ll_used2 = cpu() – ll_start

 

//查看结果

if ll_used2 > ll_used1 then

      messagebox(“提示”,”前者运行时间短!”)

else

      messagebox(“提示”,”后者运行时间短!”)

end if

 

可能有人会说,用下面的那种方式,如果在条件表达式返回false的时候,那么,if下就没有代码,这样看起来就不太舒服。的确是这样。因此,我们在写成上面的那种方式时,尽量保持不要使用not运算,而保持条件表达式本身就返回希望的true值。
第三种情况:
if condition1 then

      //condition1

elseif condition2 then

      //condition2  

elseif condition3 then

      //condition3

else

      //other

end if

choose case /*expression*/

      case /*item*/

             /*statementblock*/

      case /*item*/

             /*statementblock*/

      case else

             /*statementblock*/

end choose

 

对于形如这样的表达式,我想我们一般都没去考虑先后顺序。但是,其实我们应该把最可能发生的情况,放在前面,这样可以避免在对一大堆条件进行判断后,才到我们真正需要运行代码的地方。
第四种情况:
for … to …

     

      if condition then

             //true

      else

             //false

      end if

     

next

if condition then

      //true

      for … to …

             //code goes here

      next

else

      //false

      for … to …

             //code goes here

      next

end if

 

尽管下面这种书写方式,看起来好象代码多了一些,但是却极大的避免了在每个循环中都进行条件判断。其实,一个原则就是,我们应当尽量避免在循环中进行条件判断,而是把条件判断放到循环体的外面进行。

 

其实,真正对于pb语言有特殊性的,也就是第一种情况,对于后面三种情况,对于别的编程语言,我想也同样适用。

 

这是我的一点体会,谬误的地方请大家指正。

 

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » PB代码优化-数据库专栏,其他相关
分享到: 更多 (0)

相关推荐

  • 暂无文章