假设我有一个来自 SQL 查询的传入值,如下所示:
grok = Foo.select(:foo_attr1, :foo_attr2).first
foo_attr2
是一个可为空的字段。现在假设我需要对输出进行处理(如果存在)。
krug = grok.foo_attr2.try(:bar).try(:baz)
gnar = grok.foo_attr2 && grok.foo_attr2.bar.baz # Assumes bar will always return output that can be baz'd
这两种操作哪一种更好用,为什么?
using gnar = grok.foo_attr2 && grok.foo_attr2.bar.baz
使用 Ruby 的逻辑运算符肯定会更快。尽管try http://apidock.com/rails/Object/try由 Rails 引入并做了额外的if-else
有条件的检查。从代码:
# File activesupport/lib/active_support/core_ext/object/try.rb, line 41
def try(*a, &b)
if a.empty? && block_given?
yield self
else
public_send(*a, &b) if respond_to?(a.first)
end
end
好吧,这是一个基准来准确显示我想说的内容:
class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
else
public_send(*a, &b) if respond_to?(a.first)
end
end
end
class Foo
attr_reader :a
def initialize(a = nil)
@a = a
end
end
require "benchmark"
bar = Foo.new
baz = Foo.new(1)
n = 10000000
Benchmark.bm(40) do |x|
x.report("try"){ n.times { bar.a.try(:class).try(:to_s) } }
x.report("&& "){ n.times { baz.a && baz.a.class.to_s } }
end
结果是:
user system total real
try 10.800000 0.030000 10.830000 ( 10.829770)
&& 3.940000 0.010000 3.950000 ( 3.944375)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)