PHP Dependency Injection Container Performance Benchmarks

Share this article

Most frameworks and larger PHP applications utilize a Dependency Injection Container with the goal of a more maintainable codebase. However, this can have an impact on performance. As loading times matter, keeping sites fast is important as ever. Today I’m going to benchmark several PHP Dependency Injection containers to see what their relative performance is like.

For those unfamiliar with the concept, a Dependency Injection Container is a piece of software which automatically builds an object tree. For example, consider a User object which requires a Database instance.

$user = new User(new Database());

A Dependency Injection Container can be used to automatically construct the object tree without needing to provide the parameters manually:

$user = $container->get('User');

Each time this is called, a user object will be created with the database object “injected”.

There are several well known (and not so well known) containers available for PHP:

  • PHP-DI, a popular DI Container
  • Symfony\DependencyInjection, the the Dependency Injection Container provided by the Symfony framework
  • Zend\Di the Dependency Injection Container provided by Zend Framework
  • Orno\Di, a lesser known container with limited features but developed with performance in mind
  • Dice, another lesser known container with a focus on being lightweight. Full disclosure, I’m the author of this container, but I’ll be nothing short of entirely objective in this analysis.
  • Aura.Di, a fairly popular container with minimal features

A word on Pimple: Although Pimple is advertised as a Dependency Injection Container, retrieving an object from the container always returns the same instance, which makes Pimple a Service Locator rather than a Dependency Injection Container and as such, cannot be tested.

Although all the containers support different features, this benchmark will cover the basic functionality required by a Dependency Injection Container. That is, creating objects and injecting dependencies where they’re needed.

Which aspects of dependency injection will be measured?

  1. Execution time
  2. Memory Usage
  3. Number of files included. Although this has very little impact on performance it’s a good indicator of how lightweight and portable a library is. If you have to ship hundreds files with your project because of your DI choice, it can heavily impact the overall weight of your own application.

Testing environment

All tests were run on the same machine running Arch Linux (3.15 Kernel), PHP 5.5.13 and the latest versions of each container as of 03/07/2014.

All execution time numbers presented are an average of 10 runs after discarding any that are over 20% slower than the fastest.

Test 1 – Create an instance of an object

This test uses each container to create a simple object 10,000 times

Without a Dependency Injection Container, this would be written as:

for ($i = 0; $i < 10000; $i++) {
      $a = new A;
    }

Test code (on github): Aura, Dice, Orno\Di, PHP-DI, Symfony\DependencyInjection, Zend\Di

Test 1 - Execution Time

As you can see, there’s two clear camps here. Aura, Dice and Orno being roughly ten times faster than PHP-DI, Symfony and Zend\DI.

Test 1 - Memory Usage

Similar to Execution Time, there are two distinct groups with Symfony sitting somewhere in the middle ground.

Test 1 - Number of Files

This is very telling of how lightweight each container is and goes some way towards explaining the memory usage differences. It should be noted that a lot of the files used by Zend\Di are common framework files so if you’re using Zend Framework, then using Zend\Di will not incur the same memory overhead as files will likely be reused elsewhere in your application.

Similarly, PHP-DI heavily relies on Doctrine libraries. If you’re using Doctrine in your project, then the memory overhead of PHP-DI is reduced.

However, It’s nice to see that Symfony\DependencyInjection, despite being part of the framework stack is entirely standalone and works without any dependencies from other Symfony projects.

Aura, Dice and Orno do not have any external dependencies and this helps keep their file counts down.

Test 2 – Ignoring autoloading

As loading files can impact performance and both Zend and PHP-DI loaded a significant number of files, the same test was conducted ignoring the autoloader time by first creating a single instance of the class, ensuring any required classes were autoloaded before measuring the time.

This may also have triggered any internal caching done by the container but the same treatment was applied to each container to keep it fair

Equivalent PHP code:

for ($i = 0; $i < 10000; $i++) {
          $a = new A;
    }

Test code (on github): Aura, Dice, Orno\Di, PHP-DI, Symfony\DependencyInjection, Zend\Di

Test 2 - Execution Time

Test 2 - Execution Time

Test 2 - Execution Time

As expected, memory usage is unchanged and performance is slightly better as the autoloader time isn’t being measured. However, this shows that PHP-DI, even loading 42 files has a negligible impact on the total execution time and the relative performance remains the same, loading dozens of files is not the cause of PHP-DI and Zend\DI having relatively slow performance.

Even after ignoring the overhead of loading files, there are still two distinct ballparks here. Aura, Dice and Orno are very similar in performance and memory usage while PHP-DI, Zend and Symfony are only in competition with each other.

All the tests going forward will ignore the autoloading time to ensure it’s truly the container’s performance that is being measured.

Test 3 – Deep object graph

This test is done by having the containers construct this set of objects 10,000 times:

for ($i = 0; $i < 10000; $i++) {
        $j = new J(new I(new H(new G(new F(new E(new D(new C(new B(new A())))))))));
    }

Test code (on github): Aura, Dice, Orno\Di, PHP-DI, Symfony\DependencyInjection, Zend\Di

Note: As you can see by looking at the test code, Symfony, PHP-DI and Aura require considerably more configuration code than the other containers to perform this test. The configuration time was not included in the test.

Test 3 - Execution Time

Again, there’s very little difference between the top 3, with Dice 20% faster than Aura and 70% faster than Orno. All three are considerably faster than Zend, PHP-DI and Symfony. The difference between the three top containers is so slight in real terms that you would never notice the speed difference outside an artificial benchmark like this.

Zend, PHP-DI and to a lesser extent Symfony are slow here. Zend takes 37 seconds to perform a task Dice manages in under 1 second; certainly not a trivial difference. Yet again, Symfony takes the lead among the big name containers.

Test 3 - Memory Usage

Test 3 - Memory Usage

Memory and file counts are consistent with what we’ve seen in other tests.

Test 4 – Fetching a Service from the container

DI Containers also have to store and retrieve services which will be reused throughout the application. This test fetches a single instance from the container repeatedly.

Pure PHP Equivalent:

$a = new A;
    for ($i = 0; $i < 10000; $i++) {
      $a1 = $a;
    }

Test code (on github): Aura, Dice, Orno\Di, PHP-DI, Symfony\DependencyInjection, Zend\Di

Test 4 - Execution Time

This is unexpected based on previous results. All the containers except Zend and Symfony are roughly equal with just 0.01s separating the top 4 results. Symfony is not far behind, but Zend is well over ten times slower than the others.

Test 4 - Memory Usage

Test 4 - Number of Files

Memory usage and number of files results are becoming predictable with the same division between the containers that we’ve seen in execution time throughout.

Test 5 – Inject a service

The final test is to see how quickly an object can be constructed and have a service injected. This takes the format:

$a = new A;
    for ($i = 0; $i < 10000; $i++) {
        $b = new B($a);
    }

Test code (on github): Aura, Dice, Orno\Di, PHP-DI, Symfony\DependencyInjection, Zend\Di

Test 5 - Execution Time

Interestingly, Aura has taken a slight lead in this test. However, it’s not quite a like-for-like test as Symfony and Aura require several lines of explicit configuration while the other containers automatically resolve the dependency. The time taken to configure the container was not part of the benchmark.

Surprisingly, PHP-DI is the slowest at this task, with Zend taking its position ahead of PHP-DI and Symfony for the first time.

Test 5 - Memory Usage

Test 5 - Number of Files

Conclusion

On performance alone, Dice, Aura and Orno are all strong competitors, Dice is fastest overall and Aura fastest in the final test. The difference between the two distinct groups is apparent but its interesting to compare features of each container. Number of features and performance do not quite correlate as you’d expect. Both PHP-DI and Dice contain unique features but PHP-DI takes a heavy performance hit for doing so. Aura, although fast, requires a lot of manual configuration and does, as you’d expect, have very minimal features whereas Dice and Orno have very similar performance but require a lot less code to configure.

Symfony is very much in the middle ground in all tests, although configuring it, as with Aura, is a much more difficult task as neither support type hinted parameters. If you’re looking for a container from a well known project, then Symfony has to be the container of choice if performance is important.

That said, if pure performance is what you’re after then Dice and Aura are the clear winners with Orno very close behind. However, it’s worth taking a look at configuration syntax and features of each to see which you would prefer working with as the performance difference between Dice, Aura and Orno is negligible for any real application.

All the code for the tests is available on github. Please note: The github repository contains copies of the libraries tested rather than using composer to include them in the project, this is to ensure that you can run the code with the exact versions I tested and get the same results.

Frequently Asked Questions (FAQs) on PHP Dependency Injection Container Performance Benchmarks

What is the significance of PHP Dependency Injection Container Performance Benchmarks?

PHP Dependency Injection Container Performance Benchmarks are crucial in understanding the efficiency and speed of different dependency injection containers. These benchmarks provide a comparative analysis of various containers, helping developers make informed decisions about which container to use based on their specific needs. They offer insights into the performance of each container in terms of memory usage and time consumption, which are critical factors in optimizing the performance of PHP applications.

How does PHP Dependency Injection improve code quality?

Dependency Injection (DI) in PHP improves code quality by promoting loose coupling, enhancing testability, and increasing code reusability. By injecting dependencies, the components become more independent, making the code easier to modify and test. It also encourages single responsibility principle as each class does only what it’s supposed to do, leading to cleaner and more maintainable code.

What are the different types of Dependency Injection in PHP?

There are three main types of Dependency Injection in PHP: Constructor Injection, Setter Injection, and Interface Injection. Constructor Injection is where the dependencies are provided through a class constructor. Setter Injection involves providing the dependencies via methods. Interface Injection requires the dependent class to implement an interface which will inject the dependency.

How does a Dependency Injection Container work in PHP?

A Dependency Injection Container in PHP, also known as a Service Container, manages the instantiation and configuration of services or objects in an application. It acts as a factory that is responsible for creating and returning instances of dependencies. It also manages shared instances, ensuring that a single instance is returned each time a shared service is requested.

What factors should I consider when choosing a Dependency Injection Container?

When choosing a Dependency Injection Container, consider factors such as ease of use, performance, community support, and compatibility with your project. Performance is particularly important, and this is where PHP Dependency Injection Container Performance Benchmarks come in handy. They provide a comparative analysis of the performance of various containers, helping you make an informed decision.

How does Dependency Injection contribute to better testing in PHP?

Dependency Injection makes testing easier by decoupling the dependencies of a class. This allows for dependencies to be mocked or stubbed during testing, enabling you to test classes in isolation. It also makes it easier to write unit tests, as you can inject mock dependencies that provide predictable responses, making your tests more reliable and easier to write.

Can I use Dependency Injection in any PHP project?

Yes, Dependency Injection can be used in any PHP project, regardless of its size or complexity. It’s a design pattern that promotes code reusability, modularity, and testability, making it a valuable tool for any PHP developer.

What is the impact of Dependency Injection on application performance?

While Dependency Injection can introduce a slight overhead due to the additional abstraction layer, the impact on application performance is generally negligible. The benefits of improved code quality, testability, and maintainability often outweigh any minor performance costs.

How does Dependency Injection relate to the SOLID principles in PHP?

Dependency Injection is closely related to the SOLID principles, particularly the Dependency Inversion Principle (DIP). DIP states that high-level modules should not depend on low-level modules, but both should depend on abstractions. Dependency Injection allows for this by enabling you to inject dependencies as interfaces or abstract classes, rather than concrete classes.

Can I use multiple Dependency Injection Containers in a single PHP project?

While it’s technically possible to use multiple Dependency Injection Containers in a single PHP project, it’s generally not recommended. Using multiple containers can lead to code that is harder to manage and understand. It’s usually better to choose one container that best fits your project’s needs and stick with it.

Tom ButlerTom Butler
View Author

Tom Butler is a web developer and university lecturer. He has a PhD in the area of software engineering best practices and enjoys evaluating different approaches to programming problems.

aurabenchmarksdependency injectiondidiceframeworkOOPHPperformanceperformance-toolsPHPphpdisymfonyZend
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week