Rails活动记录效率:Model.Create在块内与Model.Create(Array)

时间:2011-10-10 20:15:50

标签: ruby-on-rails activerecord

以下哪一项会更有效率吗?

#Array is an array of hashes


Array.each do |a|
  #some logic to clean up the record for creation
  Model.create!(a)
end

VS

Array.each_with_index do |a,i|
  #some logic to clean up the Array for creation
end
Model.create!(Array)

1 个答案:

答案 0 :(得分:1)

source code之前有一个检查,它对集合执行收集,然后递归调用create。在这种情况下,使用第一种方法会更有效率,因为它使用的操作更少,并且只会进行一次is_a?(Array)检查。

源代码:

# File activerecord/lib/active_record/base.rb, line 504
def create(attributes = nil, options = {}, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create(attr, options, &block) }
  else
    object = new(attributes, options)
    yield(object) if block_given?
    object.save
    object
  end
end
相关问题