优化循环内的地图

时间:2016-06-01 06:30:20

标签: ruby

我有一个哈希数组的数据集

[
  {:last_name=>"Smith", :first_name=>"John", :city=>"New York City", :birthdate=>"5/29/1986"},
  {:last_name=>"Bar", :first_name=>"Foo", :city=>"Chicago", :birthdate=>"5/29/1986"},
  ...
]

我想按特定顺序打印值。目前我这样做:

def print(dataset, select_fields)
  output = ''
  dataset.each do |set|
    output += select_fields.map { |key| set[key] }.join(' ') + "\n"
  end
  puts output
end

因为我在map内呼叫each我相信这很慢。也许O(n²)慢?

有没有办法优化这个?使用Ruby 2.2.1

2 个答案:

答案 0 :(得分:1)

据我所知,您可以执行以下操作。

-bash: syntax error near unexpected token `('

请参阅Hash#values_at

答案 1 :(得分:1)

我的打印机在我的机器上快了大约30%。我很确定有些人能比我做得更快。通常尝试迭代一次特定的数组。顺便说一下 - 当你测试代码时,避免任何看跌,因为它会大大减慢你的测试速度。

set = [
  {:last_name=>"Smith", :first_name=>"John", :city=>"New York City", :birthdate=>"5/29/1986"},
  {:last_name=>"Bar", :first_name=>"Foo", :city=>"Chicago", :birthdate=>"5/29/1986"},
]

def my_print(dataset, select_fields)  
  output = ''
  dataset.each do |set|
    select_fields.each do |sf|
      output << "#{set[sf]} "
    end
    output[-1] = "\n"
  end  
  output
end

def your_print(dataset, select_fields)
  output = ''
  dataset.each do |set|
    output += select_fields.map { |key| set[key] }.join(' ') + "\n"
  end
  output  
end

Benchmark.bm do |bm|
  bm.report do
    1_000_000.times do
      my_print(set, [:first_name, :last_name])
    end
  end
end

Benchmark.bm do |bm|
  bm.report do
    1_000_000.times do
      your_print(set, [:first_name, :last_name])
    end
  end
end