search
HomeBackend DevelopmentPHP TutorialSample code that explains the performance of PHP magic functions in detail

I once remembered that Bird Brother Laruence mentioned that it was not recommended to use "Magic Method". From then on, whenever magic methods were used, I would subconsciously think about it, is this a good way to take pictures? Since I have been busy with work and learning new knowledge in the past one to two years, I have not done any in-depth exploration on this road and it has been in a daze. This year is a year for me to study in depth, so now I must do some research on this issue. The problem is settled. Let’s first take a look at what Bird Brother Laruence once mentioned on his blog:

When I share the PPT with my colleagues in the company, some people will question that the magic method is not allowed to be used?

Optimization The suggestion is a suggestion to prevent people from abusing and using it unscrupulously. If you can realize what is slow and what is fast when writing code, so as to avoid unnecessary calls to magic methods, that is this optimization It is suggested that the effect you are pursuing is

Doubt

  1. Is the magic method really poor in performance?

  2. Is there still a problem with the performance of using magic methods in PHP7?

  3. How should we use magic methods reasonably?

Plan

Faced with my doubts, my plan is:

  • Statistical comparison between using the magic method and not using it The time difference between magic method script execution

  • Continuously execute the script n times under PHP5.6.26-1

  • The average/minimum statistical execution time Value/maximum value

  • Continuously execute the script n times under PHP7.0.12-2

  • Statistics on the average/minimum value/maximum execution time Value

Currently my personal ability is limited and I can only use this method. If you have a better plan or suggestion, you can tell me, thank you, haha~

test

construct

First of all, let’s take a look at the experiment of constructor functionconstruct. The php script is as follows:

<?php
/**
 * 魔术方法性能探索
 *
 * 构造函数
 *
 * @author TIGERB <http://www.php.cn/;
 */

require(&#39;./function.php&#39;);
if (!isset($argv[1])) {
    die(&#39;error: variable is_use_magic is empty&#39;);
}
$is_use_magic = $argv[1];

/**
 * 构造函数使用类名
 */
class ClassOne
{
    public function classOne()
    {
        # code...
    }
}

/**
 * 构造函数使用魔术函数construct
 */
class ClassTwo
{
    public function construct()
    {
        # code...
    }
}

$a = getmicrotime();
if ($is_use_magic === &#39;no_magic&#39;) {
    new ClassOne();
}else {
    new ClassTwo();
}
$b = getmicrotime();

echo  ($b-$a) . "\n";
  • PHP5.6 The data without using the magic method is as follows, the unit is microsecond μm

// PHP5.6中连续调用脚本10000次
sh test 10000 no_magic php5 construct

// 运行数据统计脚本
sh analysis ./logs/construct_no_magic_php5.log 10000

// 结果
avg: 34μm
max: 483μm
min: 26μm
  • The data using the magic method for PHP5.6 is as follows, the unit is microsecond μm

// PHP5.6中连续调用脚本10000次
sh test 10000 magic php5 construct

// 运行数据统计脚本
sh analysis ./logs/construct_magic_php5.log 10000

// 结果
avg: 28μm
max: 896μm
min: 20μm
  • PHP7.0 does not use the magic method. The data is as follows, in microseconds μm

// PHP7.0中连续调用脚本10000次
sh test 10000 no_magic php construct

// 运行数据统计脚本
sh analysis ./logs/construct_no_magic_php.log 10000

// 结果
avg: 19μm
max: 819μm
min: 13μm
  • PHP7.0 uses magic The method data is as follows, in microseconds μm

// PHP7.0中连续调用脚本10000次
sh test 10000 magic php construct

// 运行数据统计脚本
sh analysis ./logs/construct_magic_php.log 10000

// 结果
avg: 14μm
max: 157μm
min: 10μm

From the above data we can see:

The average execution time of a script using construct as the constructor is faster For using the class name as the constructor, is about 5 to 6 microseconds faster , whether in php5.6 or php7.0.

call

Next, let’s take a look at the call experiment. The php script is as follows:

<?php
/**
 * 魔术方法性能探索
 *
 * 构造函数
 *
 * @author TIGERB <http://www.php.cn/;
 */

require(&#39;./function.php&#39;);
if (!isset($argv[1])) {
    die(&#39;error: variable is_use_magic is empty&#39;);
}
$is_use_magic = $argv[1];

/**
 * 构造函数使用类名
 */
class ClassOne
{
    public function construct()
    {
        # code...
    }

    public function test()
    {
        # code...
    }
}

/**
 * 构造函数使用魔术函数construct
 */
class ClassTwo
{
    public function construct()
    {
        # code...
    }

    public function call($method, $argus)
    {
        # code...
    }
}

$a = getmicrotime();
if ($is_use_magic === &#39;no_magic&#39;) {
    $instance = new ClassOne();
    $instance->test();
}else {
    $instance = new ClassTwo();
    $instance->test();
}
$b = getmicrotime();

echo  ($b-$a) . "\n";
  • PHP5.6 does not use the magic method. The data is as follows, The unit is microsecond μm

// PHP5.6中连续调用脚本10000次
sh test 10000 no_magic php5 call

// 运行数据统计脚本
sh analysis ./logs/call_no_magic_php5.log 10000

// 结果
avg: 27μm
max: 206μm
min: 20μm
  • PHP5.6 uses the magic method data as follows, the unit is microsecond μm

// PHP5.6中连续调用脚本10000次
sh test 10000 magic php5 call

// 运行数据统计脚本
sh analysis ./logs/call_magic_php5.log 10000

// 结果
avg: 29μm
max: 392μm
min: 22μm
  • PHP7.0 does not use the magic method. The data is as follows, in microseconds μm

// PHP7.0中连续调用脚本10000次
sh test 10000 no_magic php call

// 运行数据统计脚本
sh analysis ./logs/call_no_magic_php.log 10000

// 结果
avg: 16μm
max: 256μm
min: 10μm
  • PHP7.0 uses the magic method. The data is as follows, in microseconds. μm

// PHP7.0中连续调用脚本10000次
sh test 10000 magic php call

// 运行数据统计脚本
sh analysis ./logs/call_magic_php.log 10000

// 结果
avg: 18μm
max: 2459μm
min: 11μm

We can see from the above data:

The average execution time of a script using call is slower than not using it, It is about 2 slower Microseconds, whether in php5.6 or php7.0.

callStatic

Next, let’s take a look at the callStatic experiment. The php script is as follows:

<?php
/**
 * 魔术方法性能探索
 *
 * 静态重载函数
 *
 * @author TIGERB <http://www.php.cn/;
 */

require(&#39;./function.php&#39;);
if (!isset($argv[1])) {
    die(&#39;error: variable is_use_magic is empty&#39;);
}
$is_use_magic = $argv[1];

/**
 * 存在test静态方法
 */
class ClassOne
{
    public function construct()
    {
        # code...
    }

    public static function test()
    {
        # code...
    }
}

/**
 * 使用重载实现test
 */
class ClassTwo
{
    public function construct()
    {
        # code...
    }

    public static function callStatic($method, $argus)
    {
        # code...
    }
}

$a = getmicrotime();
if ($is_use_magic === &#39;no_magic&#39;) {
    ClassOne::test();
}else {
    ClassTwo::test();
}
$b = getmicrotime();

echo  ($b-$a) . "\n";
  • PHP5.6 does not use magic method data as follows, The unit is microsecond μm

// PHP5.6中连续调用脚本10000次
sh test 10000 no_magic php5 callStatic

// 运行数据统计脚本
sh analysis ./logs/callStatic_no_magic_php5.log 10000

// 结果
avg: 25μm
max: 129μm
min: 19μm
  • PHP5.6 uses the magic method data as follows, the unit is microsecond μm

// PHP5.6中连续调用脚本10000次
sh test 10000 magic php5 callStatic

// 运行数据统计脚本
sh analysis ./logs/callStatic_magic_php5.log 10000

// 结果
avg: 28μm
max: 580μm
min: 20μm
  • PHP7.0 does not use the magic method. The data is as follows, in microseconds μm

// PHP7.0中连续调用脚本10000次
sh test 10000 no_magic php callStatic

// 运行数据统计脚本
sh analysis ./logs/callStatic_no_magic_php.log 10000

// 结果
avg: 14μm
max: 130μm
min: 9μm
  • PHP7.0 uses the magic method. The data is as follows, in microseconds. μm

// PHP7.0中连续调用脚本10000次
sh test 10000 magic php callStatic

// 运行数据统计脚本
sh analysis ./logs/callStatic_magic_php.log 10000

// 结果
avg: 14μm
max: 159μm
min: 10μm

We can see from the above data:

The average execution time of scripts using callStatic in php5.6 is slower than not using it, About 3 microseconds slower ;The average execution time of a script using callStatic in php7.0 is roughly equal to that without callStatic;

set

Next, let’s go Take a look at the set experiment, the php script is as follows:

<?php
/**
 * 魔术方法性能探索
 *
 * 设置私有属性set
 *
 * @author TIGERB <http://www.php.cn/;
 */

require(&#39;./function.php&#39;);
if (!isset($argv[1])) {
    die(&#39;error: variable is_use_magic is empty&#39;);
}
$is_use_magic = $argv[1];

/**
 * 实现公共方法设置私有属性
 */
class ClassOne
{
    /**
     * 私有属性
     *
     * @var string
     */
    private $someVariable = &#39;private&#39;;

    public function construct()
    {
        # code...
    }

    public function setSomeVariable($value = &#39;&#39;)
    {
        $this->someVariable = $value;
    }
}

/**
 * 使用_set设置私有属性
 */
class ClassTwo
{
    /**
     * 私有属性
     *
     * @var string
     */
    private $someVariable = &#39;private&#39;;

    public function construct()
    {
        # code...
    }

    public function set($name = &#39;&#39;, $value = &#39;&#39;)
    {
        $this->$name = $value;
    }
}

$a = getmicrotime();
if ($is_use_magic === &#39;no_magic&#39;) {
    $instance = new ClassOne();
    $instance->setSomeVariable(&#39;public&#39;);
}else {
    $instance = new ClassTwo();
    $instance->someVariable = &#39;public&#39;;
}
$b = getmicrotime();

echo  ($b-$a) . "\n";
  • PHP5.6 does not use the magic method. The data is as follows, in microseconds μm

// PHP5.6中连续调用脚本10000次
sh test 10000 no_magic php5 set
// 运行数据统计脚本
sh analysis ./logs/set_no_magic_php5.log 10000

// 结果
avg: 31μm
max: 110μm
min: 24μm
  • PHP5.6 uses the magic method and the data is as follows, the unit is microsecond μm

// PHP5.6中连续调用脚本10000次
sh test 10000 magic php5 set
// 运行数据统计脚本
sh analysis ./logs/set_magic_php5.log 10000

// 结果
avg: 33μm
max: 138μm
min: 25μm
  • PHP7.0 does not use the magic method and the data is as follows, the unit is micron Second μm

// PHP7.0中连续调用脚本10000次
sh test 10000 no_magic php set
// 运行数据统计脚本
sh analysis ./logs/set_no_magic_php.log 10000

// 结果
avg: 15μm
max: 441μm
min: 11μm
  • PHP7.0 uses the magic method data as follows, the unit microsecond μm

// PHP7.0中连续调用脚本10000次
sh test 10000 magic php set
// 运行数据统计脚本
sh analysis ./logs/set_magic_php.log 10000

// 结果
avg: 17μm
max: 120μm
min: 11μm

is passed above We can see from the data:

The average execution time of scripts using set is slower than not using it, about 2 microseconds slower, whether in php5.6 or php7.0 .

get

Next, let’s take a look at the get experiment. The php script is as follows:

<?php
/**
 * 魔术方法性能探索
 *
 * 读取私有属性get
 *
 * @author TIGERB <http://www.php.cn/;
 */

require(&#39;./function.php&#39;);
if (!isset($argv[1])) {
    die(&#39;error: variable is_use_magic is empty&#39;);
}
$is_use_magic = $argv[1];

/**
 * 实现公共方法获取私有属性
 */
class ClassOne
{
    /**
     * 私有属性
     *
     * @var string
     */
    private $someVariable = &#39;private&#39;;

    public function construct()
    {
        # code...
    }

    public function getSomeVariable()
    {
        return $this->someVariable;
    }
}

/**
 * 使用_get获取私有属性
 */
class ClassTwo
{
    /**
     * 私有属性
     *
     * @var string
     */
    private $someVariable = &#39;private&#39;;

    public function construct()
    {
        # code...
    }

    public function get($name = &#39;&#39;)
    {
        return $this->$name;
    }
}

$a = getmicrotime();
if ($is_use_magic === &#39;no_magic&#39;) {
    $instance = new ClassOne();
    $instance->getSomeVariable();
}else {
    $instance = new ClassTwo();
    $instance->someVariable;
}
$b = getmicrotime();

echo  ($b-$a) . "\n";
  • PHP5.6不使用魔术方法数据如下,单位微秒μm

// PHP5.6中连续调用脚本10000次
sh test 10000 no_magic php5 get
// 运行数据统计脚本
sh analysis ./logs/get_no_magic_php5.log 10000

// 结果
avg: 28μm
max: 590μm
min: 20μm
  • PHP5.6使用魔术方法数据如下,单位微秒μm

// PHP5.6中连续调用脚本10000次
sh test 10000 magic php5 get
// 运行数据统计脚本
sh analysis ./logs/get_magic_php5.log 10000

// 结果
avg: 28μm
max: 211μm
min: 22μm
  • PHP7.0不使用魔术方法数据如下,单位微秒μm

// PHP7.0中连续调用脚本10000次
sh test 10000 no_magic php get
// 运行数据统计脚本
sh analysis ./logs/get_no_magic_php.log 10000

// 结果
avg: 16μm
max: 295μm
min: 10μm
  • PHP7.0使用魔术方法数据如下,单位微秒μm

// PHP7.0中连续调用脚本10000次
sh test 10000 magic php get
// 运行数据统计脚本
sh analysis ./logs/get_magic_php.log 10000

// 结果
avg: 19μm
max: 525μm
min: 12μm

通过上面的数据我们可以看出:

在php5.6中使用get的脚本执行的平均时间是要大致等于不使用get的;在php7.0中使用get的脚本执行的平均时间是要慢于不使用, 大概慢3微秒

结语

这里主要测试了construct(), call(), callStatic(), get(), set()这五个常用的且可有其他实现方式代替的魔法函数。通过上面的测试再回来解答我的疑惑

  1. 魔术方法真的性能比较差吗?

答:除了使用construct之外,这里使用其他的魔法方法的时间大致慢10微妙以内。

  1. PHP7里使用魔术方法的性能还是存在问题吗?

答:在PHP7中使用与不使用魔术方法之间的差异和在PHP5.6中近乎一致。

  1. 我们应该如何合理的使用魔术方法?

答:通过整个测试我们可以看出使不使用魔法方法这之间的执行时间差异大致都是在10微妙以内的,所以如果魔法方法可以很好的节省我们的开发成本和优化我们的代码结构,我们应该可以考虑牺牲掉这不到10微妙。而construct是要快的,所以使用construct应该没什么异议。

The above is the detailed content of Sample code that explains the performance of PHP magic functions in detail. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.