Table of Contents
百度工程师讲PHP函数的实现原理及性能分析(三),php函数
Home php教程 php手册 百度工程师讲PHP函数的实现原理及性能分析(三),php函数

百度工程师讲PHP函数的实现原理及性能分析(三),php函数

Jun 13, 2016 am 09:04 AM
php function Callback Implementation principle engineer Performance analysis Baidu

百度工程师讲PHP函数的实现原理及性能分析(三),php函数

常用php函数实现及介绍

count
count是我们经常用到的一个函数,其功能是返回一个数组的长度。
count这个函数,其复杂度是多少呢? 一种常见的说法是count函数会遍历整个数组然后求出元素个数,因此复杂度是O(n)。那实际情况是不是这样呢?我们回到count的实现来看一下,通过源码可以发现,对于数组的count操作,函数最终的路径是zif_count-> php_count_recursive-> zend_hash_num_elements,而zend_hash_num_elements的行为是 return ht->nNumOfElements,可见,这是一个O(1)而不是O(n)的操作。实际上,数组在php底层就是一个hash_table,对于hash表,zend中专门有一个元素nNumOfElements记录了当前元素的个数,因此对于一般的count实际上直接就返回了这个值。由此,我们得出结论: count是O(1)的复杂度,和具体数组的大小无关。
非数组类型的变量,count的行为时怎样?对于未设置变量返回0,而像int、double、string等则会返回1

strlen
Strlen用于返回一个字符串的长度。那么,他的实现原理是如何的呢?我们都知道在c中strlen是一个o(n)的函数,会顺序遍历字符串直到遇到\0,然后出长度。Php中是否也这样呢?答案是否定的,php里字符串是用一个复合结构来描述,包括指向具体数据的指针和字符串长度(和c++中string类似),因此 strlen就直接返回字符串长度了,是常数级别的操作。另外,对于非字符串类型的变量调用strlen,它会首先将变量强制转换为字符串再求长度,这点需要注意。

isset和array_key_exists
这两个函数最常见的用法都是判断一个 key是否在数组中存在。但是前者还可以用于判断一个变量是否被设置过。如前文所述,isset并非真正的函数,因此它的效率会比后者高很多。推荐用它代替array_key_exists。
array_push和array[]
两者都是往数组尾部追加一个元素。不同的是前者可以一次push多个。他们最大的区别在于一个是函数一个是语言结构,因此后者效率要更高。因此如果只是普通的追加元素,建议使用array []。

rand和mt_rand
两者都是提供产生随机数的功能,前者使用 libc标准的rand。后者用了 Mersenne Twister 中已知的特性作为随机数发生器,它可以产生随机数值的平均速度比 libc 提供的 rand() 快四倍。因此如果对性能要求较高,可以考虑用mt_rand代替前者。我们都知道,rand产生的是伪随机数,在C中需要用srand显示指定种子。但是在php中,rand会自己帮你默认调用一次srand,一般情况下不需要自己再显示的调用。需要注意的是,如果特殊情况下需要调用srand时,一定要配套调用。就是说srand对于rand,mt_srand对应srand,切不可混合使用,否则是无效的。

sort和 usort
两者都是用于排序,不同的是前者可以指定排序策略,类似我们C里面的qsort和C++的sort。在排序上两者都是采用标准的快排来实现,对于有排序需求的,如非特殊情况调用php提供的这些方法就可以了,不用自己重新实现一遍,效率会低很多。原因见前文对于用户函数和内置函数的分析比对。

urlencode和rawurlencode
这两个都是用于 url编码, 字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数。两者唯一的区别在于对于空格,urlencode会编码为+,而 rawurlencode会编码为%20。一般情况下除了搜索引擎,我们的策略都是空格编码为%20。因此采用后者的居多。注意的是encode和 decode系列一定要配套使用。

strcmp系列函数
这一系列的函数包括strcmp、 strncmp、strcasecmp、strncasecmp,实现功能和C函数相同。但也有不同,由于php的字符串是允许\0出现,因此在判断的时候底层使用的是memcmp系列而非strcmp,理论上来说更快。另外由于php直接能获取到字符串长度,因此会首先这方面的检查,很多情况下效率就会高很多了。

is_int和is_numeric
这两个函数功能相似又不完全相同,使用的时候一定需要注意他们的区别。Is_int:判断一个变量类型是否是整数型,php变量中专门有一个字段表征类型,因此直接判断这个类型即可,是一个绝对 O(1)的操作 Is_numeric:判断一个变量是否是整数或数字字符串,也就是说除了整数型变量会返回true之外,对于字符串变量,如果形如”1234”,”1e4”等也会被判为true。这个时候会遍历字符串进行判断。

总结及建议

总结:
通过对函数实现的原理分析和性能测试,我们总结出以下一些结论
1. Php的函数调用开销相对较大。
2. 函数相关信息保存在一个大的hash_table中,每次调用时通过函数名在hash表中查找,因此函数名长度对性能也有一定影响。
3. 函数返回引用没有实际意义
4. 内置php函数性能比用户函数高很多,尤其对于字符串类操作。
5. 类方法、普通函数、静态方法效率几乎相同,没有太大差异
6. 除去空函数调用的影响,内置函数和同样功能的C函数性能基本差不多。
7. 所有的参数传递都是采用引用计数的浅拷贝,代价很小。
8. 函数个数对性能影响几乎可以忽略

建议:

因此,对于php函数的使用,有如下一些建议
1. 一个功能可以用内置函数完成,尽量使用它而不是自己编写php函数。
2. 如果某个功能对性能要求很高,可以考虑用扩展来实现。
3. Php函数调用开销较大,因此不要过分封装。有些功能,如果需要调用的次数很多本身又只用1、2行代码就行实现的,建议就不要封装调用了。
4. 不要过分迷恋各种设计模式,如上一条描述,过分的封装会带来性能的下降。需要考虑两者的权衡。Php有自己的特点,切不可东施效颦,过分效仿java的模式。
5. 函数不宜嵌套过深,递归使用要谨慎。
6. 伪函数性能很高,同等功能实现下优先考虑。比如用isset代替array_key_exists
7. 函数返回引用没有太大意义,也起不到实际作用,建议不予考虑。
8. 类成员方法效率不比普通函数低,因此不用担心性能损耗。建议多考虑静态方法,可读性及安全性都更好。
9. 如不是特殊需要,参数传递都建议使用传值而不是传引用。当然,如果参数是很大的数组且需要修改时可以考虑引用传递。

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

deepseek web version entrance deepseek official website entrance deepseek web version entrance deepseek official website entrance Feb 19, 2025 pm 04:54 PM

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.

Baidu Apollo releases Apollo ADFM, the world's first large model that supports L4 autonomous driving Baidu Apollo releases Apollo ADFM, the world's first large model that supports L4 autonomous driving Jun 04, 2024 pm 08:01 PM

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

How to use performance analysis tools to analyze and optimize Java functions? How to use performance analysis tools to analyze and optimize Java functions? Apr 29, 2024 pm 03:15 PM

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.

ai tool recommendation ai tool recommendation Nov 29, 2024 am 11:08 AM

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.

How do C++ libraries perform timing and performance analysis? How do C++ libraries perform timing and performance analysis? Apr 18, 2024 pm 10:03 PM

Timing and profiling in C++ can be done by using timing libraries such as and to measure the execution time of code snippets. In actual combat, we can use the function library to measure the calculation time of the Fibonacci sequence function, and the output result is: Result:102334155Time:0.048961seconds. In addition, performance analysis includes techniques such as profiling tools, logging, and performance counters.

Similarities and differences between PHP functions and Flutter functions Similarities and differences between PHP functions and Flutter functions Apr 24, 2024 pm 01:12 PM

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.

Baidu Robin Li led a team to visit PetroChina to discuss the intelligence of the oil and gas industry Baidu Robin Li led a team to visit PetroChina to discuss the intelligence of the oil and gas industry May 07, 2024 pm 06:13 PM

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

What are the AI ​​tools? What are the AI ​​tools? Nov 29, 2024 am 11:11 AM

AI tools include: Doubao, ChatGPT, Gemini, BlenderBot, etc.

See all articles