Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ a.users {}

However, this solution is kind of hacky.

## Object Shape Optimization

In Ruby 3.2, a new optimization was introduced that relies on tracking "object shape", and has negative interactions with dynamically added instance variables (introduced after initialization-time). See [here](https://bugs.ruby-lang.org/issues/18776) for details, or [here](https://railsatscale.com/2023-10-24-memoization-pattern-and-object-shapes/) for an explanation of the relevance, but fundamentally Memery has substantial advantages over standard memoization techniques here - it introduces only _one_ new instance variable after initialization (`@_memery_memoized_values`). For particularly performance-critical classes however, you may wish to reduce that to zero; if so, you can call `setup_memery_cache!` in the initializer of your class, and it will set the instance variable before the object shape is determined.

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/tycooon/memery.
Expand Down
7 changes: 7 additions & 0 deletions lib/memery.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ def method_visibility(klass, method_name)
end

module InstanceMethods
# This method is not _functionally necessary_, but if called in the
# initializer of a class, it allows that class to avoid any issue with the
# "object shape optimization" introduced in Ruby 3.2.
def setup_memery_cache!
@_memery_memoized_values = {}
end

def clear_memery_cache!
@_memery_memoized_values = {}
end
Expand Down
16 changes: 16 additions & 0 deletions spec/memery_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,14 @@ class H
memoize :x, :y, ttl: 3
end

class I
include Memery

def initialize
setup_memery_cache!
end
end

RSpec.describe Memery do
subject(:a) { A.new }

Expand Down Expand Up @@ -475,4 +483,12 @@ class H
include_examples "works correctly"
end
end

describe "#setup_memery_cache!" do
let(:i) { I.new }

specify do
expect(i).to be_instance_variable_defined("@_memery_memoized_values")
end
end
end