loophp / memoize
Memoize a closure.
Fund package maintenance!
drupol
Installs: 6 186
Dependents: 0
Suggesters: 0
Security: 0
Stars: 13
Watchers: 5
Forks: 1
Open Issues: 2
Requires
- php: >= 7.4
Requires (Dev)
- drupol/php-conventions: ^2.0.3
- friends-of-phpspec/phpspec-code-coverage: ^5
- infection/infection: ^0.20
- infection/phpspec-adapter: ^0.1.1
- loophp/phpspec-time: ^1.1
- phpspec/phpspec: ^7
- phpstan/phpstan-strict-rules: ^0.12
- vimeo/psalm: ^4
README
PHP Memoize
Description
Memoizer class for callable.
From wikipedia:
In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
This library help you to memoize callable or closures.
Features
- Provides a Memoizer class.
- Immutable.
- Stateless.
Installation
With composer:
composer require loophp/memoize
Usage
<?php declare(strict_types=1); namespace App; include 'vendor/autoload.php'; use Closure; use Generator; use loophp\memoize\Memoizer; $fibonacci = static function (int $number) use (&$fibonacci): int { return (1 >= $number) ? $number : $fibonacci($number - 1) + $fibonacci($number - 2); }; $fibonacciMemoized = static function (int $number) use (&$fibonacciMemoized): int { return (1 >= $number) ? $number : $fibonacciMemoized($number - 1) + $fibonacciMemoized($number - 2); }; $fibonacciMemoized = Memoizer::fromClosure($fibonacciMemoized); function bench(Closure $closure, ...$arguments): array { $eval = static function (Closure $closure, ...$arguments): Generator { yield microtime(true); yield $closure(...$arguments); yield microtime(true); }; $result = iterator_to_array($eval($closure, ...$arguments)); return [ $result[1], $result[2] - $result[0], ]; } var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacci, 30))); // ~3 seconds var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacciMemoized, 30))); // ~0.0003 seconds
Code style, code quality, tests and benchmarks
The code style is following PSR-12 plus a set of custom rules, the package drupol/php-conventions is responsible for this.
Every time changes are introduced into the library, Github CI run the tests and the benchmarks.
The library has tests written with PHPSpec.
Feel free to check them out in the spec
directory. Run composer phpspec
to trigger the tests.
PHPInfection is used to ensure that your code is properly tested, run composer infection
to test your code.
Contributing
See the file CONTRIBUTING.md but feel free to contribute to this library by sending Github pull requests.