search
HomeBackend DevelopmentPHP TutorialPHP class method online performance test_PHP tutorial

PHP class method online performance test

A friend in a group asked a question two months ago. He said: "Now their company's project has a module whose online performance is very poor. The problem has not been found for a long time. The boss was furious. The boss asked him to record the execution time of all class methods for analysis, and it should not affect the current project performance. "The boss asked him to record this information to analyze the specific places that affect performance, and remove it after the project has been running for a period of time. This requirement leads to two problems. The first is how to monitor the execution time of all class methods in this module. The second is how to complete it without affecting the performance of the current project (the performance itself is very poor). Here we will do this Two questions to analyze:

1. How to monitor the execution time of all class methods in this module

The first thing he thought about this problem was to add a piece of code to record the time before all class method processing, calculate the running time before returning the data, and then record the log. This method must be feasible, and it will not have a great impact on performance, but... I won't do it anyway. Programmers are lazy, and they are all very smart. We are not coders. If it is implemented like this , then the amount of code to be changed is too large, and meaningless and technical work will be repeated for a long time. Secondly, when I delete it again in the future, I will crash. Of course, none of my friends would do this, so I learned about this strange need.

How to solve it? It is really difficult to solve such a task. We can use __call() and __callStatic() to overload class methods. Before php5.3, static methods could only be added one by one. , thanks to the new __callStatic() magic method in php5.3. Some people may ask that these two magic methods are only useful when the class method does not exist. How can they achieve this requirement? We will look at the code for this question later. Let’s analyze the second question below.

2. How can it be completed without affecting the performance of the current project

Why do I say there is this problem? It was indeed there when analyzing the requirements before, but the solution was already mentioned when answering the first question. I think using __call() and __callStatic() to overload class methods is relatively simple to implement, and it is also good for existing methods. Project performance impact is minimal.

We mainly discuss some other methods in this question. In fact, there are many extensions to achieve performance analysis, such as xdebug, xhprof, etc. It is known that xdebug has a large performance loss and is not suitable for use in a formal environment. xhprof has a relatively small performance loss. Can be used in formal environments. So why not use xhprof? There are three points: 1. The performance loss is slightly larger; 2. The log recording format is inflexible, which causes trouble in log analysis; 3. Some functions cannot be counted, and serious errors will occur (such as: call_user_func_array)

Now that the solution has been determined, let’s take a look at a demo first

/**
 * 类方法性能监听
 *
 * @author 戚银  thinkercode@sina.com
 * @date	2015-05-31 22:09
 */
class demo {

	/**
	 * 普通类方法
	 *
	 * @access public
	 * @return void
	 */
	public function test1(){
		for($i=0; $i<100; ++$i){

		}
	}

	/**
	 * 静态方法
	 *
	 * @access public
	 * @return void
	 */
	public static function test2(){
		for($i=0; $i<100; ++$i){

		}
	}
}

Look at the demo class above. There are two methods in it, one ordinary method and one static method. The way our business layer calls it is as follows:

<?php
(new demo())->test1();
demo::test2();

We ensure that one principle is not to change the code outside the class, but only adjust the class to implement it. Below I use __call() and __callStatic() to overload the class method.

<?php
/**
 * 类方法性能监听
 *
 * @author 戚银  thinkercode@sina.com
 * @date	2015-05-31 22:09
 */
class demo {

	/**
	 * 普通类方法
	 *
	 * @access public
	 * @return void
	 */
	public function _test1(){
		for($i=0; $i<100; ++$i){

		}
	}

	/**
	 * 静态方法
	 *
	 * @access public
	 * @return void
	 */
	public static function _test2(){
		for($i=0; $i<100; ++$i){

		}
	}

	/**
	 * 类魔术方法
	 *
	 * @access public
	 * @param string $name
	 * @param array	 $arguments
	 * @return mixed
	 */
	public function __call($name, $arguments){
		$startTime = microtime(true);
		$data = call_user_func_array(array($this, &#39;_&#39;.$name), $arguments);
		echo microtime(true) - $startTime;
		return $data;
	}

	/**
	 * 类魔术方法
	 *
	 * @access public
	 * @param string $name
	 * @param array	 $arguments
	 * @return mixed
	 */
	public static function __callStatic($name, $arguments){
		$startTime = microtime(true);
		$data = call_user_func_array(array(__CLASS__, &#39;_&#39;.$name), $arguments);
		echo microtime(true) - $startTime;
		return $data;
	}
}

In this code we have added the __call() and __callStatic() methods. It is useless if we only add these two methods, because the previous business layer code has not changed and the calling method exists. To make the called method not exist and only change the class itself, we can only add an underscore before the method name (this rule is determined by ourselves), and then when we call these two methods, we find that the execution time of the two methods is output.

Several problems have been discovered in this implementation. There are still a lot of code changes, and each class has to be added, which is very tiring... In fact, it is easy to implement by making use of the tools at hand. Using inheritance is a good way. Write these two methods into a base class, and then all classes will inherit this base class. For class method name replacement, except for constructors and destructors, you can directly use the editor to replace them in batches, and you can change them back later.

Note: If implemented using inheritance, the __CLASS__ of the __callStatic() method needs to be adjusted.

Here is implemented by adding an underscore before the class method so that the business layer cannot find the class method. In fact, this example can also be implemented by adjusting the method visibility, but the visibility implementation method has the following disadvantages:

1. If you want to adjust it back after adjustment, it is very likely that the visibility of class methods will be wrong, and you will not know which methods have been adjusted.

2. Adjusting visibility is only effective for class public methods, not for protected and private methods

Of course, if you only record the performance of public methods of a class, you can use changing method visibility, but you must remember to add a mark on the attention that the method has been changed, and it must be changed from public to private, because if there is class inheritance This class cannot access this method.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1011353.htmlTechArticlephp class method online performance test A friend in the group asked a question two months ago. He said: “Now their company’s project has a module whose performance is very poor online for a long time...
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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool