gpt4 book ai didi

php - 性能 : Empty string or null in PHP

转载 作者:行者123 更新时间:2023-12-02 05:41:05 27 4
gpt4 key购买 nike

由于 PHP 在字符串操作和输出中对它们一视同仁,我想知道最佳实践是什么,分配/连接一个 null 值或一个空字符串:

$lang = 'lang';
$suffix = null;
$lang .= $suffix;

$desc = 'name';
$suffix = '';
$desc .= $suffix;

内联条件也可能是这种情况:

<div class="item<?= $is_selected ? ' selected' : null ?>"></div>

<div class="item<?= $is_selected ? ' selected' : '' ?>"></div>

我知道它不会影响整体性能,但它可以与使用双引号或单引号相比吗?

最佳答案

> php --version
PHP 5.3.12 with Suhosin-Patch (cli) (built: May 9 2012 11:44:31)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
with Suhosin v0.9.33, Copyright (c) 2007-2012, by SektionEins GmbH
php > $start = microtime(true); for( $i = 0; $i < 1000000; ++$i ) { $str = 'foo'; $str .= null; } printf('%.5f', microtime(true) - $start);
0.15258
php > $start = microtime(true); for( $i = 0; $i < 1000000; ++$i ) { $str = 'foo'; $str .= ''; } printf('%.5f', microtime(true) - $start);
0.11397

运行了几次,每次都得到非常相似的结果。

结论:

  • 将空字符串附加到字符串比将 null 附加到空字符串稍微快
  • 除非您在具有数十亿 次迭代的循环中执行此操作,否则从性能的角度来看这并不重要,因此请使用具有更好语义意义的那个。

关于php - 性能 : Empty string or null in PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10952612/

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