快速获取数组元素的索引红宝石 [英] Quickly get index of array element in Ruby
问题描述
由于我有一个巨大的数组,并从它的值。我想在数组中的价值指标。是否有任何其他方式,而再调用阵列#指数
来得到它?这个问题源于需要保持真正巨大的数组,并调用阵列#指数
的时间大量的。
Given I have a HUGE array, and a value from it. I want to get index of the value in array. Is there any other way, rather then call Array#index
to get it? The problem comes from the need of keeping really huge array and calling Array#index
enormous amount of times.
经过几次尝试,我发现的缓存的内部元素通过存储结构与(价值指数)
字段,而不是本身的价值指标给出了性能的一大步(20X次夺冠)。
After a couple of tries I found that caching indexes inside elements by storing structs with (value, index)
fields instead of the value itself gives a huge step in performance (20x times win).
不过我不知道是否有发现连接的元素的索引没有缓存(或有一个很好的缓存技术,这将提高了性能)更方便的方法。
Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).
推荐答案
转换的数组哈希值。然后寻找的关键。
Convert the array into a hash. Then look for the key.
array = ['a', 'b', 'c']
hash = Hash[array.map.with_index.to_a] # => {"a"=>0, "b"=>1, "c"=>2}
hash['b'] # => 1
这篇关于快速获取数组元素的索引红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!