loophp/memoize

Memoize a closure.

Fund package maintenance!
drupol

5.0.2 2021-01-17 10:29 UTC

This package is auto-updated.

Last update: 2021-03-17 10:51:12 UTC


README

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

<?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.