将两个字符串添加在一起的最佳方法是什么?

2022-08-30 19:25:16

我在这里读到(我想在编码上)将字符串加在一起是坏习惯,就好像它们是数字一样,因为像数字一样,字符串不能改变。因此,将它们加在一起会创建一个新字符串。所以,我想知道,在专注于性能时,将两个字符串加在一起的最佳方法是什么?

这四种方法中哪一种更好,还是有另一种方法更好?

//Note that normally at least one of these two strings is variable
$str1 = 'Hello ';
$str2 = 'World!'; 
$output1 = $str1.$str2; //This is said to be bad

$str1 = 'Hello ';
$output2 = $str1.'World!'; //Also bad

$str1 = 'Hello';
$str2 = 'World!';
$output3 = sprintf('%s %s', $str1, $str2); //Good?
//This last one is probaply more common as:
//$output = sprintf('%s %s', 'Hello', 'World!');

$str1 = 'Hello ';
$str2 = '{a}World!';
$output4 = str_replace('{a}', $str1, $str2);

这重要吗?


答案 1

带点的字符串串联绝对是三种方法中最快的一种。您将始终创建一个新字符串,无论您喜欢与否。最有可能的是最快的方法是:

$str1 = "Hello";
$str1 .= " World";

不要像这样将它们放在双引号中,因为这会为解析字符串内的符号产生额外的开销。$result = "$str1$str2";

如果您打算仅将其用于带有echo的输出,请使用echo的功能,您可以为其传递多个参数,因为这不会生成新字符串:

$str1 = "Hello";
$str2 = " World";
echo $str1, $str2;

有关PHP如何处理插值字符串和字符串串联的更多信息,请查看Sarah Goleman的博客


答案 2

您总是要创建一个新字符串,将两个或多个字符串连接在一起。这不一定是“坏的”,但在某些情况下(例如紧密循环中的数千/数百万个串联),它可能会对性能产生影响。我不是PHP人,所以我不能给你任何关于连接字符串的不同方式的语义的建议,但是对于单个字符串串联(或只是几个),只是让它可读。您不会看到其中数量较少的性能下降。


推荐