将两个字符串添加在一起的最佳方法是什么?
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);
这重要吗?