Project

ddmemoize

0.01
Repository is archived
No commit activity in last 3 years
No release in over 3 years
Adds support for memoizing functions
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

~> 1.0
~> 2.0
 Project Readme

Gem version Gem downloads Build status Code Climate Code Coverage

DDMemoize

DDMemoize adds support for memoizing Ruby functions.

For example, the following Fibonacci implementation runs quickly (in O(n) rather than in O(2^n)):

class FibFast
  DDMemoize.activate(self)

  memoized def run(n)
    if n == 0
      0
    elsif n == 1
      1
    else
      run(n - 1) + run(n - 2)
    end
  end
end

Features:

  • Supports memoizing functions on frozen objects
  • Releases memoized values when needed in order to reduce memory pressure
  • Optionally records metrics

Installation

Add this line to your application's Gemfile:

gem 'ddmemoize'

And then execute:

$ bundle

Or install it yourself as:

$ gem install ddmemoize

Usage

First, require ddmemoize and enable it using DDMemoize.activate:

require 'ddmemoize'

class FibFast
  DDMemoize.activate(self)

  # …
end

To memoize a function, call memoize with the name of the function:

  def run(n)
    # …
  end
  memoize :run

Alternatively, prepend memoized to the function definition:

  memoized def run(n)
    # …
  end

Do not memoize functions that depend on mutable state.

Metrics

To activate metrics, call DDMemoize.enable_metrics after requiring ddmemoize.

To print the collected metrics, call DDMemoize.print_metrics:

DDMemoize.print_metrics
memoization │ hit   miss       %
────────────┼───────────────────
FibFast#fib │ 998   1001   49.9%

Development

Install dependencies:

$ bundle

Run tests:

$ bundle exec rake

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ddfreyne/ddmemoize. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the DDMemoize project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.