项目作者: loophp

项目描述 :
Memoize a closure.
高级语言: PHP
项目地址: git://github.com/loophp/memoize.git
创建时间: 2017-09-19T12:56:29Z
项目社区:https://github.com/loophp/memoize

开源协议:

下载


Latest Stable Version
GitHub stars
Total Downloads
GitHub Workflow Status
Scrutinizer code quality
Type Coverage
Code Coverage
License
Donate!
Donate!

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

  1. <?php
  2. declare(strict_types=1);
  3. namespace App;
  4. include 'vendor/autoload.php';
  5. use Closure;
  6. use Generator;
  7. use loophp\memoize\Memoizer;
  8. $fibonacci = static function (int $number) use (&$fibonacci): int {
  9. return (1 >= $number) ?
  10. $number :
  11. $fibonacci($number - 1) + $fibonacci($number - 2);
  12. };
  13. $fibonacciMemoized = static function (int $number) use (&$fibonacciMemoized): int {
  14. return (1 >= $number) ?
  15. $number :
  16. $fibonacciMemoized($number - 1) + $fibonacciMemoized($number - 2);
  17. };
  18. $fibonacciMemoized = Memoizer::fromClosure($fibonacciMemoized);
  19. function bench(Closure $closure, ...$arguments): array
  20. {
  21. $eval = static function (Closure $closure, ...$arguments): Generator {
  22. yield microtime(true);
  23. yield $closure(...$arguments);
  24. yield microtime(true);
  25. };
  26. $result = iterator_to_array($eval($closure, ...$arguments));
  27. return [
  28. $result[1],
  29. $result[2] - $result[0],
  30. ];
  31. }
  32. var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacci, 30))); // ~3 seconds
  33. 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.