Skip to content
This repository has been archived by the owner on Oct 9, 2024. It is now read-only.

loophp/memoize

Repository files navigation

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.