简体   繁体   English

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

[英]Rails active record efficiency: Model.Create inside a block vs Model.Create(Array)

Would either of the following be more efficient? 以下任一个会更有效吗?

#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)

Going by the source code there is a check which performs a collect on the collection and then recursively calls create. 按照源代码进行检查,该检查对集合执行收集,然后递归调用create。 That being the case, you would be more efficient with the first method as it uses less operations and will only do the is_a?(Array) check once. 在这种情况下,第一种方法将使用较少的操作,并且只会执行一次is_a?(Array)检查,因此会提高效率。

The source code: 源代码:

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM