gpt4 book ai didi

php - array_push() 和 $array[] 之间的区别 =

转载 作者:IT老高 更新时间:2023-10-28 11:48:38 26 4
gpt4 key购买 nike

在 PHP 手册中,( array_push ) 说..

If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

例如:

$arr = array();
array_push($arr, "stackoverflow");
print_r($arr);

$arr[] = "stackoverflow";
print_r($arr);

我不明白为什么会有很大的不同。

最佳答案

当你在 PHP 中调用一个函数(例如 array_push())时,调用会有开销,因为 PHP 必须查找函数引用,找到它在内存中的位置并执行任何操作它定义的代码。

使用 $arr[] = 'some value'; 不需要函数调用,而是直接在数据结构中实现加法。因此,当添加大量数据时,使用 $arr[] 会更快且资源效率更高。

关于php - array_push() 和 $array[] 之间的区别 =,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com