【问题标题】:Fastest way to find a String into an array of string将字符串查找到字符串数组中的最快方法
【发布时间】:2012-02-16 15:25:49
【问题描述】:

脚本必须验证一个预定义的 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

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

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

【问题讨论】:

标签: ruby arrays string loops comparison


【解决方案1】:

您可以使用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 

【讨论】:

  • 或者在你的情况下:s = Set.new(ips)
  • 你好 Alex :) .include 方法源代码似乎和我的几乎一样。还是实际上更快?
  • @Cocotton:Much faster。您还可以使用以 ip 作为键并以“真”作为值的哈希。
  • 这里明显的警告是 Set 更快,但是构建 Set 可能是一项昂贵的操作,因此您不希望构建一个集合来查询它的次数很少。跨度>
  • 对于 1240 万个短字符串的数组:a=('a'..'zzzzz').to_a; time{ a.include?('0') } #=&gt; 0.71s; time{ Set.new(a) } #=&gt; 11.2s;所以是的,创建集合的开销需要与瞬时查询的性能提升相匹配。
【解决方案2】:

您可以使用 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

【讨论】:

    【解决方案3】:

    更快的方法是:

    if ips.include?(ip)
      puts "ip exists"
      return 1
    else
      puts "ip doesn't exist"
      return nil
    end
    

    【讨论】:

    • 稍微快一点,因为 each 出现在 C 而不是 Ruby 中,但对于 Hash 或 Set,它仍然是 O(n) 与 O(1)。
    【解决方案4】:
    ips = ['10.10.10.10','10.10.10.11','10.10.10.12']
    
    ip = '10.10.10.10'
    ips.include?(ip) => true
    
    ip = '10.10.10.13'
    ips.include?(ip) => false
    

    check Documentaion here

    【讨论】:

    • 但这实际上比我的方法快吗?因为它的源代码似乎和我的几乎一样。
    • 当然更快..我在我的项目中使用过..而且当ruby中有方法时,我们为什么要编写额外的代码。
    • @dku.rajkumar 想说,.include? 应该更快,因为 .include? 是在 Array 类的 C 级别上实现的。
    【解决方案5】:

    您尝试过 Array#include 吗?功能?

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

    你可以从源代码中看到它几乎完全一样的事情,除了原生。

    【讨论】:

    • 这仍然是一个 O(n) 时间操作,因为它必须搜索数组中的每个项目(即使它在 C 中)。
    • 我知道一个枚举是可以排序的,但是我不知道如何搜索这样一个排序好的数组。可以创建一个索引数据库列来完成这项工作。
    • 即使是二分查找也是 O(log n)。散列一个项目并在散列表中查找它是一个与存储的项目数量无关的恒定时间操作。
    猜你喜欢
    • 2015-01-14
    • 1970-01-01
    • 2016-10-05
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多