Class: Lich::Common::LruIndex

Inherits:
Object
  • Object
show all
Defined in:
documented/common/gameobj.rb

Overview


Lich::Common::LruIndex — optional drop-in replacement for @@index

A size-capped Least Recently Used (LRU) cache that stores the same [GameObj, last_seen_at] tuple format as the default plain Hash, making it a transparent drop-in replacement.

Use when profiling shows @@index growing too large in very long or heavily automated sessions. Combines LRU eviction (by access recency) with the same TTL-based prune_older_than interface as prune_index!.

Usage — swap the initializer inside GameObj:

@@index = Lich::Common::LruIndex.new(2000)

How it works:

Ruby Hashes preserve insertion order. On every read (+[]+) the accessed
entry is moved to the end (most recently used). When the cap is reached
on a write (+[]=+), the first entry (least recently used) is evicted.

Instance Method Summary collapse

Constructor Details

#initialize(capacity = 2000) ⇒ LruIndex

Returns a new instance of LruIndex.



782
783
784
785
# File 'documented/common/gameobj.rb', line 782

def initialize(capacity = 2000)
  @capacity = capacity
  @store    = {}
end

Instance Method Details

#[](key) ⇒ Object



787
788
789
790
791
792
793
794
# File 'documented/common/gameobj.rb', line 787

def [](key)
  return nil unless @store.key?(key)

  # Move to end (most recently used) by delete-and-reinsert
  value = @store.delete(key)
  @store[key] = value
  value
end

#[]=(key, value) ⇒ Object



796
797
798
799
800
# File 'documented/common/gameobj.rb', line 796

def []=(key, value)
  @store.delete(key) if @store.key?(key)
  @store.shift if @store.size >= @capacity
  @store[key] = value
end

#clearObject



823
824
825
# File 'documented/common/gameobj.rb', line 823

def clear
  @store.clear
end

#delete_if(&block) ⇒ Object



827
828
829
830
# File 'documented/common/gameobj.rb', line 827

def delete_if(&block)
  @store.delete_if(&block)
  self
end

#each_value(&block) ⇒ Object



819
820
821
# File 'documented/common/gameobj.rb', line 819

def each_value(&block)
  @store.each_value(&block)
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


802
803
804
# File 'documented/common/gameobj.rb', line 802

def key?(key)
  @store.key?(key)
end

#prune_older_than(cutoff) ⇒ Object



806
807
808
809
810
811
812
813
814
815
816
817
# File 'documented/common/gameobj.rb', line 806

def prune_older_than(cutoff)
  pruned = 0
  @store.delete_if do |_key, (_obj, last_seen)|
    if last_seen < cutoff
      pruned += 1
      true
    else
      false
    end
  end
  pruned
end

#sizeObject



832
833
834
# File 'documented/common/gameobj.rb', line 832

def size
  @store.size
end