首页 > 解决方案 > 在 Ruby/RoR 中更快地处理嵌套对象

问题描述

我必须创建一个可以包含所有可能的对象组合的数组(每个对象可以包含超过 10k 条记录,例如站)。我在下面写了三个对象,但实际代码包含 8 个对象(不是 3 个)。

我的代码的问题是它非常慢并且需要几个小时才能完成。我也尝试使用 find_each 和 parallel,但我无法在嵌套的每个循环中使用它。我想知道是否有人知道让我的代码更快运行的方法。

target_objects = %w[prefecture city station].each_with_object([]) do |obj_name, arr|
  arr << obj_name.classify.constantize.all
end
test = []
target_objects.each.with_index do |objects, index|
  objects.each do |first_obj|
    test << first_obj
    target_objects[(index + 1)..-1]&.each&.with_index(index + 1) do |second_objects, second_objects_index|
      second_objects.each do |second_obj|
        test << [first_obj, second_obj]
        target_objects[second_objects_index + 1..-1]&.each&.with_index(second_objects_index + 1) do |third_objects, third_objects_index|
          third_objects.each do |third_obj|
            test << [first_obj, second_obj, third_obj]
          end
        end
      end
    end
  end
end

标签: arraysruby-on-railsrubyparallel-processingsitemap

解决方案


10k 条记录.. 使用枚举器。

(1..target_objects.size).flat_map{|size| target_objects.combination(size) }

推荐阅读