将两个字符串加在一起的最佳方法是什么? [英] What is the best way to add two strings together?

查看:114
本文介绍了将两个字符串加在一起的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某种程度上(我想到了编码恐惧症)读到,将字符串像数字一样加在一起是不好的做法,因为像数字一样,字符串不能更改.因此,将它们加在一起将创建一个新的字符串.因此,我想知道在关注性能时将两个字符串加在一起的最佳方法是什么?

I read somewehere (I thought on codinghorror) that it is bad practice to add strings together as if they are numbers, since like numbers, strings cannot be changed. Thus, adding them together creates a new string. So, I was wondering, what is the best way to add two strings together, when focusing on performance?

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

Which of these four is better, or is there another way which is better?

//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);

这有关系吗?

推荐答案

您总是要创建一个将两个或多个字符串连接在一起的新字符串.这不一定是不好的",但在某些情况下(例如紧密循环中成千上万的串联)可能会影响性能.我不是PHP专家,所以我无法就串联字符串的不同方式的语义提供任何建议,但是对于单个字符串串联(或仅几个字符串),只需使其可读即可.您不会看到它们数量很少的性能下降.

You are always going to create a new string whe concatenating two or more strings together. This is not necessarily 'bad', but it can have performance implications in certain scenarios (like thousands/millions of concatenations in a tight loop). I am not a PHP guy, so I can't give you any advice on the semantics of the different ways of concatenating strings, but for a single string concatenation (or just a few), just make it readable. You are not going to see a performance hit from a low number of them.

这篇关于将两个字符串加在一起的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆