


Baidu engineers talk about the implementation principles and performance analysis of PHP functions (3), php functions_PHP tutorial
Baidu engineers talk about the implementation principles and performance analysis of PHP functions (3), PHP functions
implementation and introduction of commonly used PHP functions
count
count is a function we often use, its function is to return the length of an array.
What is the complexity of the count function? A common saying is that the count function will traverse the entire array and find the number of elements, so the complexity is O(n). So is this actually the case? Let's go back to the implementation of count. Through the source code, we can find that for the count operation of the array, the final path of the function is zif_count-> php_count_recursive-> zend_hash_num_elements, and the behavior of zend_hash_num_elements is return ht->nNumOfElements. It can be seen that, This is an O(1) rather than O(n) operation. In fact, the array is a hash_table at the bottom of PHP. For the hash table, there is a special element nNumOfElements in zend to record the number of current elements, so for general count, this value is actually returned directly. From this, we draw the conclusion: count has a complexity of O(1) and has nothing to do with the size of the specific array.
What is the behavior of count for non-array type variables? For unset variables, 0 is returned, while int, double, string, etc. will return 1
strlen
Strlen is used to return the length of a string. So, what is his implementation principle? We all know that strlen is an O(n) function in C, which will sequentially traverse the string until it encounters
isset and array_key_exists
The most common use of these two functions is to determine whether a key exists in the array. But the former can also be used to determine whether a variable has been set. As mentioned earlier, isset is not a real function, so its efficiency will be much higher than the latter. It is recommended to use this instead of array_key_exists.
array_push and array[]
Both append an element to the end of the array. The difference is that the former can push multiple ones at one time. The biggest difference between them is that one is a function and the other is a language structure, so the latter is more efficient. Therefore, if you are just appending elements normally, it is recommended to use array [].
rand and mt_rand
Both provide the function of generating random numbers. The former uses the libc standard rand. The latter uses known features in Mersenne Twister as a random number generator, which can generate random values on average four times faster than rand() provided by libc. Therefore, if you have higher performance requirements, you can consider using mt_rand instead of the former. We all know that rand generates pseudo-random numbers. In C, you need to use srand to display the specified seed. But in php, rand will call srand once by default for you. Under normal circumstances, there is no need to explicitly call it yourself. It should be noted that if srand needs to be called under special circumstances, it must be called in conjunction. That is to say, srand corresponds to rand, and mt_srand corresponds to srand. They must not be mixed, otherwise they will be invalid.
sort and usort
Both are used for sorting. The difference is that the former can specify a sorting strategy, similar to our qsort and C sort in C. In terms of sorting, both are implemented using standard quick sorting. For those who have sorting requirements, just call these methods provided by PHP unless there are special circumstances. There is no need to re-implement it yourself, and the efficiency will be much lower. The reason can be seen in the previous analysis and comparison of user functions and built-in functions.
urlencode and rawurlencode
Both of these are used for URL encoding, all non-alphanumeric characters in the string except -_. will be replaced with a percent sign (%) followed by two hexadecimal digits. The only difference between the two is that for spaces, urlencode will be encoded as , while rawurlencode will be encoded as . In general, except for search engines, our strategy is to encode spaces as . Therefore, the latter is mostly used. Note that the encode and decode series must be used together.
strcmp series functions This series of functions include strcmp, strncmp, strcasecmp, strncasecmp, and their implementation functions are the same as C functions. But there are differences, since php strings are allowed
is_int and is_numeric
The functions of these two functions are similar but not exactly the same. You must pay attention to their differences when using them. Is_int: Determine whether a variable type is an integer type. There is a special field representation type in PHP variables, so you can directly judge this type. It is an absolute O(1) operation. Is_numeric: Determine whether a variable is an integer or a numeric string. , that is to say, in addition to integer variables that will return true, for string variables, if they are in the form of "1234", "1e4", etc., they will also be judged as true. At this time, the string will be traversed for judgment.
Summary and suggestions
Summary:
Through the principle analysis and performance testing of function implementation, we have summarized the following conclusions
1. Php's function calling overhead is relatively large.
2. Function-related information is stored in a large hash_table. Each time it is called, the function name is searched in the hash table. Therefore, the length of the function name also has a certain impact on performance.
3. Function return reference has no practical meaning
4. The performance of built-in PHP functions is much higher than that of user functions, especially for string operations.
5. The efficiency of class methods, ordinary functions, and static methods is almost the same, there is not much difference
6. Excluding the impact of empty function calls, the performance of built-in functions and C functions with the same function are basically the same.
7. All parameter transfers are shallow copies using reference counting, which costs little.
8. The impact of the number of functions on performance is almost negligible
Recommendation:
Therefore, for the use of php functions, there are some suggestions as follows
1. A function can be accomplished with a built-in function, try to use it instead of writing your own php function.
2. If a certain function has high performance requirements, you can consider using extensions to implement it.
3. Php function calls are expensive, so don't over-encapsulate them. If some functions need to be called a lot and can be implemented with only 1 or 2 lines of code, it is recommended not to encapsulate the calls.
4. Don't be overly obsessed with various design patterns. As described in the previous article, excessive encapsulation will cause performance degradation. There are trade-offs between the two that need to be considered. Php has its own characteristics, and you must not imitate the Java model too much.
5. Functions should not be nested too deeply, and recursion should be used with caution.
6. Pseudo functions have high performance and will be given priority when implementing the same functions. For example, use isset instead of array_key_exists
7. The function returning a reference does not make much sense and has no practical effect. It is recommended not to consider it.
8. Class member methods are no less efficient than ordinary functions, so there is no need to worry about performance loss. It is recommended to consider more static methods, which have better readability and security.
9. Unless there are special needs, it is recommended to use pass-by-value instead of pass-by-reference for parameter passing. Of course, if the parameter is a large array and needs to be modified, you can consider passing it by reference.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

On May 15, Baidu Apollo held Apollo Day 2024 in Wuhan Baidu Luobo Automobile Robot Zhixing Valley, comprehensively demonstrating Baidu's major progress in autonomous driving over the past ten years, bringing technological leaps based on large models and a new definition of passenger safety. With the world's largest autonomous vehicle operation network, Baidu has made autonomous driving safer than human driving. Thanks to this, safer, more comfortable, green and low-carbon travel methods are turning from ideal to reality. Wang Yunpeng, vice president of Baidu Group and president of the Intelligent Driving Business Group, said on the spot: "Our original intention to build autonomous vehicles is to satisfy people's growing yearning for better travel. People's satisfaction is our driving force. Because safety, So beautiful, we are happy to see

According to news from this site on May 7, on May 6, Robin Li, founder, chairman and CEO of Baidu, led a team to visit China National Petroleum Corporation (hereinafter referred to as "PetroChina") in Beijing and met with directors of China National Petroleum Corporation Chairman and Party Secretary Dai Houliang held talks. The two parties had in-depth exchanges on strengthening cooperation and promoting the deep integration of the energy industry with digital intelligence. PetroChina will accelerate the construction of a digital China Petroleum Corporation, strengthen cooperation with Baidu Group, promote the in-depth integration of the energy industry with digital intelligence, and make greater contributions to ensuring national energy security. Robin Li said that the "intelligent emergence" and core capabilities of understanding, generation, logic, and memory displayed by large models have opened up a broader space for imagination for the combination of cutting-edge technology and oil and gas business. Always

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

Java performance analysis tools can be used to analyze and optimize the performance of Java functions. Choose performance analysis tools: JVisualVM, VisualVM, JavaFlightRecorder (JFR), etc. Configure performance analysis tools: set sampling rate, enable events. Execute the function and collect data: Execute the function after enabling the profiling tool. Analyze performance data: identify bottleneck indicators such as CPU usage, memory usage, execution time, hot spots, etc. Optimize functions: Use optimization algorithms, refactor code, use caching and other technologies to improve efficiency.

According to news on May 31, blogger @ibinguniverse broke the news today that the Chinese version of Samsung Galaxy S24 series mobile phones will support Google search. The blogger did not disclose the specific launch time. According to Samsung’s previous introduction, the Samsung Galaxy S24 series has been equipped with many high-level AI capabilities, AI-based practical functions such as input, translation, recorder, notes, and cameras, to provide users with a more convenient and efficient comprehensive experience. Different from the overseas version, most of the AI functions of the Samsung Galaxy S24 series are provided by domestic manufacturers, such as Baidu. Previously reported, Galaxy AI deeply integrates multiple capabilities of Baidu Wenxin large model, which can provide end-side enabled call and translation functions, as well as intelligent summary brought by generative AI.

The main differences between PHP and Flutter functions are declaration, syntax and return type. PHP functions use implicit return type conversion, while Flutter functions explicitly specify return types; PHP functions can specify optional parameters through ?, while Flutter functions use required and [] to specify required and optional parameters; PHP functions use = to pass naming Parameters, while Flutter functions use {} to specify named parameters.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

This article introduces six popular AI tools, including Douyin Doubao, Wenxin Yige, Tencent Zhiying, Baidu Feipiao EasyDL, Baidu AI Studio and iFlytek Spark Cognitive Large Model. These tools cover different functions such as text creation, image generation, video editing, and AI model development. Choosing the right AI tool requires consideration of factors such as functional requirements, technical level, and cost budget. These tools provide convenient and efficient solutions for individuals and businesses in need of AI assistance.
