Baidu engineers talk about the implementation principle and performance analysis of PHP function (iii), PHP function _php Tutorial

Source: Internet
Author: User
Tags strcmp urlencode alphanumeric characters

Baidu engineers talk about the implementation principle and performance analysis of PHP function (c), PHP function


Implementation and introduction of common PHP functions

Count
Count is a function that we often use, and its function is to return the length of an array.
What is the complexity of the count function? A common argument is that the Count function traverses the entire array and then evaluates the number of elements, so the complexity is O (n). Is that the reality? We return to the implementation of count to see, through the source can be found, for the count operation of the array, the final path of the function is zif_count-> php_count_recursive-> zend_hash_num_elements, While Zend_hash_num_elements's behavior is return ht->nnumofelements, it is visible that this is an O (1) operation instead of O (n). In fact, the array at the bottom of PHP is a hash_table, for the hash table, Zend has a special element nnumofelements record the current number of elements, so for the general count actually directly returned this value. Thus, we conclude that count is the complexity of O (1), independent of the size of the specific array.
Variables of non-array type, what is the behavior of count? Returns 0 for a variable that is not set, and 1 for an int, double, string, and so on

Strlen
The strlen is used to return the length of a string. So, how does his principle of implementation work? We all know that in C, Strlen is an O (n) function that iterates through a string until it encounters a. Is this also true in PHP? The answer is no, the string in PHP is described in a composite structure, including pointers to specific data and string lengths (similar to strings in C + +), so strlen directly returns the length of the string, which is a constant-level operation. In addition, calling strlen for a variable of a non-string type, it is important to note that it first casts the variable to a string and then asks for a length.

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 if a variable has been set. As mentioned earlier, Isset is not a real function, so its efficiency is much higher than the latter. It is recommended to replace Array_key_exists.
Array_push and array[]
Both are appending an element to the tail of the array. The difference is that the former can push multiple at a time. Their biggest difference is that one function is a language structure, so the latter is more efficient. Therefore, if it is just an ordinary append element, it is recommended to use array [].

Rand and Mt_rand
Both provide the ability to generate random numbers, the former using the LIBC standard rand. The latter uses the known characteristics of the Mersenne Twister as a random number generator, which can produce random values four times times faster than Rand () provided by LIBC. Therefore, if the performance requirements are high, consider replacing the former with Mt_rand. As we all know, Rand produces pseudo-random numbers, and in c it is necessary to display the specified seed with Srand. However, in PHP, Rand will help you by default to call Srand, and generally do not need to display their own calls. It is important to note that if you need to call Srand in special cases, make sure that you call the package. That is to say srand for Rand,mt_srand correspondence Srand, must not mix use, otherwise is invalid.

Sort and Usort
Both are used for sorting, but the former can specify a sort strategy, similar to the qsort and C + + sort in our C. In the order of the two are implemented by the standard fast, for the ordering requirements, such as non-special cases call PHP to provide these methods can be, do not have to re-implement again, the efficiency is much lower. The reason for this is the analysis of the user function and the built-in function in the previous article.

UrlEncode and Rawurlencode
Both are used for URL encoding, except-_ in the string. All non-alphanumeric characters are replaced with a percent (%) followed by a two-digit hexadecimal number. The only difference between the two is that for spaces, UrlEncode is encoded as +, and Rawurlencode is encoded as%20. In general, in addition to search engines, our strategy is to encode the space as%20. So the latter is the majority of the use. Note that the encode and decode series must be used as a companion.

STRCMP Series functions
The functions of this series include strcmp, strncmp, strcasecmp, strncasecmp, and the same implementation function as the C function. But there are also differences, because the PHP string is allowed to appear, so in the judgment of the bottom of the use of the MEMCMP series rather than strcmp, theoretically faster. In addition, because PHP directly can get to the length of the string, so the first check in this respect, in many cases, the efficiency is much higher.

Is_int and Is_numeric
These two functions are functionally similar and not identical, and they must be used with the same attention to their differences. Is_int: To determine whether a variable type is an integer type, PHP variable is specifically a field characterization type, so directly judge this type can be an absolute O (1) Operation Is_numeric: Determine whether a variable is an integer or a numeric string, That is, in addition to the integer variable will return true, for the string variable, if the shape such as "1234", "1e4" and so will also be sentenced to true. This time the string will be traversed to determine.

Summary and Suggestions

Summarize:
Through the principle analysis and performance test of function realization, we summarize the following conclusions
1. PHP has a relatively expensive function call.
2. Function-related information is stored in a large hash_table, each time it is called by the function name in the hash table, so function name length has a certain effect on performance.
3. function return reference has no practical meaning
4. Built-in PHP functions are much higher performance than user functions, especially for string class operations.
5. class methods, normal functions, static methods are almost the same efficiency, not much difference
6. Except for the effect of empty function calls, the functions of the built-in function and the same function C function basically similar.
7. All parameter passing is a shallow copy of the reference count, at a very low cost.
8. The performance impact of the number of functions can be almost ignored

Suggestions:

Therefore, for the use of PHP functions, there are some suggestions
1. A function can be done with built-in functions, try to use it instead of writing PHP functions yourself.
2. If a feature has high performance requirements, consider extending it.
3. PHP function calls are expensive, so do not encapsulate them too much. Some features, if you need to call a lot of itself and only 1, 2 lines of code on the line implementation, it is recommended not to encapsulate the call.
4. Do not indulge in a variety of design patterns, as described in the previous article, excessive encapsulation will bring performance degradation. The tradeoff between the two needs to be considered. PHP has its own characteristics, must not parody, too much copy of the Java model.
5. Functions should not be nested too deep, recursive use to be cautious.
6. The performance of pseudo-function is high, and the same function is given priority. Like using Isset instead of array_key_exists.
7. The function return reference does not make much sense and does not make a practical difference, and it is recommended not to be considered.
8. Class member methods are less efficient than normal functions, so there is no need to worry about performance loss. It is recommended to consider static methods, which are more readable and more secure.
9. In the case of special needs, parameter passing suggests using a pass-through instead of a reference. Of course, reference passing can be considered if the parameter is a large array and needs to be modified.

http://www.bkjia.com/PHPjc/998810.html www.bkjia.com true http://www.bkjia.com/PHPjc/998810.html techarticle Baidu Engineers talk about the implementation principle and performance analysis of PHP functions (c), PHP functions commonly used PHP function implementation and introduction count count is a function we often use, its function is to return a ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.