查找字符串数组的最快方法

Coc*_*ton 18 ruby arrays string comparison loops

该脚本必须验证大量IP中是否存在一个预定义的IP.目前我的代码功能就像这样(说"ips"是我的IP数组,"ip"是预定义的ip)

ips.each do |existsip|
  if ip == existsip
    puts "ip exists"
    return 1
  end
end
puts "ip doesn't exist"
return nil
Run Code Online (Sandbox Code Playgroud)

有没有更快的方法来做同样的事情?

编辑:我可能错误地表达了自己.我可以做array.include吗?但我想知道的是:array.include?能给我最快结果的方法吗?

Ali*_*kau 34

你可以使用Set.它在Hash之上实现,对于大数据集更快--O(1).

require 'set'
s = Set.new ['1.1.1.1', '1.2.3.4']
# => #<Set: {"1.1.1.1", "1.2.3.4"}> 
s.include? '1.1.1.1'
# => true 
Run Code Online (Sandbox Code Playgroud)

  • 对于1240万个短字符串的数组:`a =('a'..'zzzzz').to_a; 时间{a.include?('0')}#=> 0.71s; 时间{Set.new(a)}#=> 11.2s`; 所以,是的,创建集合的开销需要值得瞬时查询的性能提升. (3认同)
  • @Cocotton:[快得多](http://stackoverflow.com/questions/5551168/performance-of-arrays-and-hashes-in-ruby/5552062#5552062).您也可以使用带有ip的Hash作为键,使用'true'作为值. (2认同)

eri*_*aio 5

您可以使用 Array#include 方法返回真/假。

http://ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F

if ips.include?(ip) #=> true
  puts 'ip exists'
else
  puts 'ip  doesn\'t exist'
end
Run Code Online (Sandbox Code Playgroud)