`
orcl_zhang
  • 浏览: 234130 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Benchmark

    博客分类:
  • ruby
阅读更多
1,length > 0和blank?和emtpy?
>> Benchmark.bm do |x|
?>  x.report{10000.times{[].blank?}}
>>  x.report{10000.times{[].empty?}}
>>  x.report{10000.times{[].length > 0}}
>> end
      user     system      total        real
  0.010000   0.000000   0.010000 (  0.006934)
  0.010000   0.000000   0.010000 (  0.008550)
  0.010000   0.000000   0.010000 (  0.009955)
=> true

2,eval和__send
>> Benchmark.bm do |x|
?>  x.report{10000.times{1+2}}
>>  x.report{10000.times{1.__send__(:+,2)}}
>>  x.report{10000.times{eval("1+2")}}
>> end
      user     system      total        real
  0.010000   0.000000   0.010000 (  0.011300)
  0.000000   0.000000   0.000000 (  0.013654)
  0.020000   0.000000   0.020000 (  0.014717)
=> true

养成良好的小习惯吧,如果在大数组里出现这些代码,速度还是有一点点的影响的。
分享到:
评论
6 楼 orcl_zhang 2010-06-30  
不明白,原来的代码为什么要这样些,大把大把的after_find,只是为了得到一个实例变量。我要将他们全部kill掉。
看看api是如何说的:
引用
The after_find and after_initialize exceptions

Because after_find and after_initialize are called for each object found and instantiated by a finder, such as Base.find(:all), we‘ve had to implement a simple performance constraint (50% more speed on a simple test case). Unlike all the other callbacks, after_find and after_initialize will only be run if an explicit implementation is defined (def after_find). In that case, all of the callback types will be called.

如果把after_find去掉之后,会出现这样的情况。
>> u=User.find(1)
>> u.instance_eval{@info}
=> nil
>> u.info
=> "ss"
>> u.instance_eval{@info}
=> "ss"
5 楼 orcl_zhang 2010-06-30  
第一遍,user中代码
  attr_accessible :code,:info
  def after_find
    @code = self.id
    @info = self.info
  end

第二遍
  def code
    @code = self.id
  end

  def info
    @info = self.info
  end

两次benchmark结果:
>> require 'benchmark'
=> []
>> Benchmark.bm do |x|
?>  x.report{100.times{User.all}}
>> end
      user     system      total        real
 79.920000   0.060000  79.980000 ( 79.990261)
 41.550000   0.020000  41.570000 ( 41.724401)






4 楼 orcl_zhang 2010-06-17  
Hooopo 写道
你这样优化没有意义。。
代码级别的速度提升是有限的。
如果一个页面好几秒应该分析一下瓶颈在哪里,是db有slow query还是rails代码或是前端页面渲染,或是缓存利用的差。。

在model里面有一些检索代码是在修改,这些只是顺手也修改的。意义不是优化,良好的习惯。我在前面已经写了
引用
养成良好的小习惯吧,如果在大数组里出现这些代码,速度还是有一点点的影响的。
我也并没用指望这点优化能起到多大的作用。
3 楼 Hooopo 2010-06-17  
你这样优化没有意义。。
代码级别的速度提升是有限的。
如果一个页面好几秒应该分析一下瓶颈在哪里,是db有slow query还是rails代码或是前端页面渲染,或是缓存利用的差。。
2 楼 orcl_zhang 2010-06-17  
Hooopo 写道
这么小的差别还是看哪个顺眼用哪个好了。。

length > 0,不是ruby风格的代码,而且效率没有empty?高,差30%。很多eval可以改成instance_eval或者__send__的都改了。现在这个项目的代码很恶心,速度不是一般的慢,一个页面好几秒,记录太多,到处改改,发现还是快了不少,其他地方的优化的空间不是很大。
大家尽量也养成比较好的习惯吧。
1 楼 Hooopo 2010-06-17  
这么小的差别还是看哪个顺眼用哪个好了。。

相关推荐

Global site tag (gtag.js) - Google Analytics