arrays - 在 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
解决方案
10k 条记录.. 使用枚举器。
(1..target_objects.size).flat_map{|size| target_objects.combination(size) }
推荐阅读
- reactjs - React Intl 与 relativeTime 格式
- docker - 如何在docker中以分离模式处理退出代码
- c# - 将值从 sortedset 复制到数组
- swiftui - 想将此代码转换为纯 SwiftUI 代码。没有自动布局,没有 UIViewRepresentable,没有 UIHostingController
- python - TypeError:'int'对象在python3中使用SET执行SQL时不可迭代
- google-cloud-firestore - Cloud FireStore基于数组元素id的数组安全规则
- java - 如何在 logback.xml 文件中调用 application.properties 值?
- python - numpy 数组的统一索引采样
- wpf - 如果项目已分组,ItemContainerGenerator.ContainerFromItem 方法返回 null
- python - python requests.get 模块未按预期工作