亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Key Takeaways
Which aspects of dependency injection will be measured?
Testing environment
Test 1 – Create an instance of an object
Test 2 – Ignoring autoloading
Test 3 – Deep object graph
Test 4 – Fetching a Service from the container
Test 5 – Inject a service
Conclusion
Frequently Asked Questions (FAQs) on PHP Dependency Injection Container Performance Benchmarks
What is the significance of PHP Dependency Injection Container Performance Benchmarks?
How does PHP Dependency Injection improve code quality?
What are the different types of Dependency Injection in PHP?
How does a Dependency Injection Container work in PHP?
What factors should I consider when choosing a Dependency Injection Container?
How does Dependency Injection contribute to better testing in PHP?
Can I use Dependency Injection in any PHP project?
What is the impact of Dependency Injection on application performance?
How does Dependency Injection relate to the SOLID principles in PHP?
Can I use multiple Dependency Injection Containers in a single PHP project?
Home Backend Development PHP Tutorial PHP Dependency Injection Container Performance Benchmarks

PHP Dependency Injection Container Performance Benchmarks

Feb 20, 2025 pm 12:23 PM

PHP Dependency Injection Container Performance Benchmarks

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?

  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:

<span>$user = new User(new Database());</span>

Test code (on github): Aura, Dice, OrnoDi, PHP-DI, SymfonyDependencyInjection, ZendDi

PHP Dependency Injection Container Performance Benchmarks

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.

PHP Dependency Injection Container Performance Benchmarks

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

PHP Dependency Injection Container Performance Benchmarks

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

PHP Dependency Injection Container Performance Benchmarks

PHP Dependency Injection Container Performance Benchmarks

PHP Dependency Injection Container Performance Benchmarks

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.

PHP Dependency Injection Container Performance Benchmarks

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.

PHP Dependency Injection Container Performance Benchmarks

PHP Dependency Injection Container Performance Benchmarks

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

PHP Dependency Injection Container Performance Benchmarks

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.

PHP Dependency Injection Container Performance Benchmarks

PHP Dependency Injection Container Performance Benchmarks

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

PHP Dependency Injection Container Performance Benchmarks

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.

PHP Dependency Injection Container Performance Benchmarks

PHP Dependency Injection Container Performance Benchmarks

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

php regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

See all articles