Ruby on rails 对象数组比字符串数组慢得多

Ruby on rails 对象数组比字符串数组慢得多,ruby-on-rails,ruby,Ruby On Rails,Ruby,使用RubyonRails3.2。我使用以下方法迭代关联,以查找是否存在照片: # Method 1 def trip_photos if (photos = trip_days.map(&:spots).flatten.map(&:photos).flatten.map) photos.each do |photo| photo.url(:picture_preview) end end end # >

使用RubyonRails3.2。我使用以下方法迭代关联,以查找是否存在照片:

  # Method 1
  def trip_photos
    if (photos = trip_days.map(&:spots).flatten.map(&:photos).flatten.map)
      photos.each do |photo|
        photo.url(:picture_preview)
      end
    end
  end
  # >> ['picture_1.jpg', 'picture_2.jpg']

  # Method 1 view
  @object.trip_photos.each do |photo|
    photo
  end


  # Method 2
  def trip_photos
    if (photos = trip_days.map(&:spots).flatten.map(&:photos).flatten.map)
      photos.each do |photo|
        photo
      end
    end
  end
  # >> [photo_object_1, photo_object_2]

  # Method 2 view
  @object.trip_photos.each do |photo|
    photo.data.url(:picture_preview)
  end
  • 方法1
    执行需要30毫秒<代码>方法2执行需要400毫秒。有什么原因吗

  • 我更喜欢
    method2
    ,因为我可以从
    photo
    获取更多数据,而不仅仅是URL,但它存在性能问题。我怎样才能解决这个问题


  • 正如Yoshiji先生所说,您可能可以重构您的请求以最小化数据收集上的循环

    改进方法1和方法2的一种方法:可以避免最后一次
    map
    每次调用,只需将集合作为
    展平所给出的数组返回即可

    # Method 2
    def trip_photos
      if (photos = trip_days.map(&:spots).flatten.map(&:photos).flatten)
        photos
      end
    end
    # >> [photo_object_1, photo_object_2]      
    

    trip\u days.map(&:spot)、flatte.map(&:photos)
    返回什么?这是一个递归循环,返回与方法1中描述的相同的结果(如果可用)。您可以尝试
    Photo.includes(:spot=>:trip\u days)。其中(:trip\u days=>{id:trip\u days.pulk(:id)})
    ,方法1不调用“数据”。方法2调用
    photo.data.url
    ,而不仅仅是
    photo.url
    。这可能是区别吗?