array_push() 与 $array[] = .... 哪个最快?

发布于 2024-07-26 12:59:24 字数 434 浏览 5 评论 0原文

我需要将从 MySQL 接收到的值添加到数组(PHP)中。 这就是我所得到的:

$players = array();

while ($homePlayerRow = mysql_fetch_array($homePlayerResult)) {
    $players[] = $homePlayerRow['player_id'];
}

这是唯一的方法吗?

另外,以下是否更快/更好?

$players = array();

while ($homePlayerRow = mysql_fetch_array($homePlayerResult)) {
    array_push($players, $homePlayerRow['player_id']);
}

I need to add values received from MySQL into an array (PHP). Here is what I've got:

$players = array();

while ($homePlayerRow = mysql_fetch_array($homePlayerResult)) {
    $players[] = $homePlayerRow['player_id'];
}

Is this the only way of doing it?

Also, is the following faster/better?

$players = array();

while ($homePlayerRow = mysql_fetch_array($homePlayerResult)) {
    array_push($players, $homePlayerRow['player_id']);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乞讨 2024-08-02 12:59:24

这取决于...

文档说

“如果使用 array_push() 向数组添加一个元素,最好使用 $array[] =,因为这样就没有调用函数的开销。”

来源:https://www.php.net/array_push

因此,归结为您有多少数据想要在任何特定时刻塞入该数组。

此外,还有一个后退。 如果使用 array_push 调用数组时引用的数组不存在,则会出现错误。 如果您使用 $array[],将为您创建数组。

It depends...

Documentation says,

"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."

Source: https://www.php.net/array_push

So it boils down to how much data you want to cram into that array at any particular moment.

Additionally, there's a fall-back. If the array-referenced doesn't exist when you call it using array_push, you'll bump an error. If you use $array[], the array will be created for you.

独留℉清风醉 2024-08-02 12:59:24

您可以运行它并看到 array_push 在某些情况下速度较慢:

http ://snipplr.com/view/759/speed-test-arraypush-vs-array/

运行您的代码。 享受。

You can run it and see that array_push is slower in some cases:

http://snipplr.com/view/759/speed-test-arraypush-vs-array/

Run your code. Enjoy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文