Key Takeaways
- Dependency Injection Containers (DIC) are a key tool for maintaining codebases in larger PHP applications and frameworks, but can impact performance. Some of the well-known DICs for PHP include PHP-DI, SymfonyDependencyInjection, ZendDi, OrnoDi, Dice, and Aura.Di.
- Performance of DICs is measured in terms of execution time, memory usage, and number of files included. The last metric is especially important as it can greatly affect the overall weight of an application.
- Among the tested containers, Dice, Aura, and Orno were the fastest, with Dice being the overall fastest. PHP-DI, despite having unique features, had a significant performance hit. Symfony, while more difficult to configure, performed in the middle ground and would be the preferred choice for those looking for a container from a well-known project.
- Despite the performance differences, the choice of a DIC should also consider configuration syntax and features. The performance difference between Dice, Aura, and Orno is negligible for any real application, hence, developers should choose based on which they would prefer working with.
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.
<span>$user = new User(new Database());</span>
A Dependency Injection Container can be used to automatically construct the object tree without needing to provide the parameters manually:
<span>$user = $container->get('User');</span>
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
- SymfonyDependencyInjection, the the Dependency Injection Container provided by the Symfony framework
- ZendDi the Dependency Injection Container provided by Zend Framework
- OrnoDi, 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?
- Execution time
- Memory Usage
- 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:
<span>$user = new User(new Database());</span>
Test code (on github): Aura, Dice, OrnoDi, PHP-DI, SymfonyDependencyInjection, ZendDi
As you can see, there’s two clear camps here. Aura, Dice and Orno being roughly ten times faster than PHP-DI, Symfony and ZendDI.
Similar to Execution Time, there are two distinct groups with Symfony sitting somewhere in the middle ground.
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 ZendDi are common framework files so if you’re using Zend Framework, then using ZendDi 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 SymfonyDependencyInjection, 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:
<span>$user = new User(new Database());</span>
Test code (on github): Aura, Dice, OrnoDi, PHP-DI, SymfonyDependencyInjection, ZendDi
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 ZendDI 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:
<span>$user = $container->get('User');</span>
Test code (on github): Aura, Dice, OrnoDi, PHP-DI, SymfonyDependencyInjection, ZendDi
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.
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.
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:
<span>$user = new User(new Database());</span>
Test code (on github): Aura, Dice, OrnoDi, PHP-DI, SymfonyDependencyInjection, ZendDi
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.
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:
<span>$user = $container->get('User');</span>
Test code (on github): Aura, Dice, OrnoDi, PHP-DI, SymfonyDependencyInjection, ZendDi
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.
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.
The above is the detailed content of PHP Dependency Injection Container Performance Benchmarks. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.