🌈 A lazy-initializing high performance service map
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
build
examples
src/LazyMap
tests Removing workaround for polyfractal/athletic#13, since it's fixed in … Nov 11, 2013
.gitignore Importing project structure Nov 4, 2013
.scrutinizer.yml Adding scrutinizer-ci config Nov 5, 2013
.travis.yml Adding HHVM to build matrix May 1, 2014
CONTRIBUTING.md Importing project structure Nov 4, 2013
LICENSE Importing project structure Nov 4, 2013
README.md
composer.json Removing workaround for polyfractal/athletic#13, since it's fixed in … Nov 11, 2013
phpdox.xml.dist
phpmd.xml.dist Importing project structure Nov 4, 2013
phpunit.xml.dist

README.md

Lazy Map

This small library aims at providing a very simple and efficient map of lazy-instantiating objects.

Build Status Coverage Status Scrutinizer Quality Score Total Downloads Latest Stable Version Latest Unstable Version Dependency Status

Installation

The suggested installation method is via composer:

php composer.phar require ocramius/lazy-map:1.0.*

Usage

The current implementation is very simple and allows to define a map of "services" through a LazyMap\CallbackMap:

$map = new \LazyMap\CallbackLazyMap(function ($name) {
    $object = new \stdClass();

    $object->name = $name;

    return $object;
});

var_dump($map->foo);
var_dump($map->bar);
var_dump($map->{'something special'});

Purpose

The idea behind the library is to avoid un-efficient lazy-loading operations like following:

private function getSomething($name)
{
    if (isset($this->initialized[$name]) || array_key_exists($name, $this->initialized)) {
        return $this->initialized[$name];
    }

    return $this->initialized[$name] = new Something($name);
}

This reduces overhead greatly when you'd otherwise call getSomething() thousands of times. That's especially useful when mapping a lot of different services and iterating over them over and over again.

Performance

LazyMap actually performs much better than the "un-efficient" example that I've shown above. You can look directly at the performance test suite for details on the tested implementations, but here are some results for you to have an idea of the boost:

Initialized Map Performance:

Method Name Ops/s Relative
initializedArrayPerformance 2,277,272.90002 100.00%
initializedArrayMapPerformance 1,536,988.76108 148.16%
initializedLazyMapPerformance 4,446,227.23514 51.22%

Un-Initialized Map Performance:

Method Name Ops/s Relative
unInitializedArrayPerformance : 1,091,720.80627 100.00%
unInitializedArrayMapPerformance 688,132.30083 158.65%
unInitializedLazyMapPerformance: 912,191.90744 119.68%