class LookupBy::Caching::LRU

Public Class Methods

new(max_size) click to toggle source

In Ruby 1.9+, Hash is ordered.

bugs.ruby-lang.org/issues/8312 In Ruby 2.0, Hash#shift is bugged and horribly slow.

require 'benchmark/ips'
hash, i, N = {}, 0, 20_000_000; while i < N; hash[i] = true; i += 1; end

Benchmark.ips do |x|
  x.report("shift") { hash.shift }
  x.report("first") { hash.delete hash.first[0] }
end

Ruby | shift | first ———–-------—— 1.9.3-p484 | 264k | 89k 1.9.3-p551 | 945k | 370k 2.0.0-p0 | 0k | 70k 2.0.0-p643 | 0k | 272k 2.1.5 | 4947k | 3557k 2.2.1 | 6801k | 4457k rbx-2.5.2 | 609k | 409k

# File lib/lookup_by/caching/lru.rb, line 27
def initialize(max_size)
  @data = {}
  self.max_size = max_size
end

Public Instance Methods

[](key) click to toggle source
# File lib/lookup_by/caching/lru.rb, line 40
def [](key)
  found = true
  value = @data.delete(key) { found = false }

  @data[key] = value if found
end
[]=(key, value) click to toggle source
# File lib/lookup_by/caching/lru.rb, line 47
def []=(key, value)
  @data.delete(key)
  @data[key] = value
  @data.shift if @data.length > @max_size
end
clear() click to toggle source
# File lib/lookup_by/caching/lru.rb, line 53
def clear
  @data.clear
end
count() click to toggle source
# File lib/lookup_by/caching/lru.rb, line 57
def count
  @data.length
end
delete(key) click to toggle source
# File lib/lookup_by/caching/lru.rb, line 61
def delete(key)
  @data.delete(key)
end
each() { |pair| ... } click to toggle source
# File lib/lookup_by/caching/lru.rb, line 65
def each
  @data.to_a.each do |pair|
    yield pair
  end
end
fetch(key) { |key| ... } click to toggle source
# File lib/lookup_by/caching/lru.rb, line 71
def fetch(key)
  found = true
  value = @data.delete(key) { found = false }

  if found
    @data[key] = value
  elsif block_given?
    value = @data[key] = yield key
    @data.shift if @data.length > @max_size
    value
  else
    raise KeyError, "key not found: %p" % [key]
  end
end
key?(key) click to toggle source
# File lib/lookup_by/caching/lru.rb, line 86
def key?(key)
  @data.key?(key)
end
max_size=(size) click to toggle source
# File lib/lookup_by/caching/lru.rb, line 32
def max_size=(size)
  raise ArgumentError.new(:maxsize) if size < 1

  @max_size = size

  @data.shift while @data.length > @max_size
end
size() click to toggle source
# File lib/lookup_by/caching/lru.rb, line 90
def size
  @data.size
end
to_a() click to toggle source
# File lib/lookup_by/caching/lru.rb, line 94
def to_a
  @data.to_a
end
to_h() click to toggle source
# File lib/lookup_by/caching/lru.rb, line 98
def to_h
  @data.dup
end
values() click to toggle source
# File lib/lookup_by/caching/lru.rb, line 102
def values
  @data.values
end