PHP函数的参数按值传递跟引用传递哪个效率更高
PHP函数的参数按值传递和引用传递哪个效率更高?
按值传递
function abc($t){<br /> $c=$t;<br />}
引用传递
function abc(&$t){<br /> $c=$t;<br />}
我把很长的一篇文章赋给变量$t,然后循环10万次 abc($t), 发现按值传递的速度要比引用传递快不少
我无法理解的是,为什么PHP中按值传递反而快呢?理论上讲按值传递有个复制的过程,而引用是直接指向内存地址,应该引用传递更快才对,希望各位能解答我的问题。
另外有什么讲PHP执行效率的书籍,推荐下,谢谢
------解决思路----------------------
在PHP中,对于&引用操作符采用的是“写时拷贝”的原理,就是除非发生写操作,指向同一个地址的变量或者对象是不会被拷贝的。
当你在使用&符号把$a数组传入函数时,PHP引擎会认为这个函数可能会导致对$a的改变,此时就会自动为$b生产一个$a的数据拷贝,重新申请一块内存进行存储。这就是前面提到的“写时拷贝”概念。
你可以测试对比一下用值传递与引用传递执行效率,比如外面加入一个循环1000次,看看运行的耗时,结果会让你知道不正确使用PHP引用&符号会导致性能下降30%以上。
因为多了一项拷贝的操作,所以会导致系统资源的耗费(尤其是大数组的情况),因此,在PHP中,要尽量使用值传递,而少用引用传递。
------解决思路----------------------
所以说是要不断地学习
由#4
125544 一开始的内存占用量
126640 定义了 $a 之后,增加了 1096
f1:126656 传值调用 f1,增加了 16(应该是一个指向$a的指针之类的东西)
f1:126688
126656 从 f1 返回后,尚有 16 未释放
f2:126672 传引用调用 f2,增加了 16
f2:125656
125656 从 f2 返回后,内存占有还原(126656)
可以看到:以往资料上说的创建副本、写时拷贝等等都已经过时了!

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

AI Hentai Generator
Generate AI Hentai for free.

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



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Validator can be created by adding the following two lines in the controller.

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.
