变量串联的单引号还是双引号

变量串联的单引号还是双引号

本文介绍了变量串联的单引号还是双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将变量(例如$name)连接到现有的字符串(例如$string)中是否更好:

Is it better to concatenate a variable (say, $name) into an existing string (say, $string) like this:

$string='Hi, my name is '.$name

或将变量嵌入到字符串中,如下所示:

or to embed the variable in the string like this:

$string="Hi, my name is $name";

还是使用像这样的函数更好:

or is it better to use a function like this:

$string=sprintf("Hi, my name is %s",$name);

在处理器时间/效率方面哪个更好?

Which is better in terms of processor time/efficiency?

推荐答案

进行测试的每个人都得出结论,使用单引号在性能上略有提高.最后,单引号仅导致串联,而双引号则强制解释器解析变量的完整字符串.

Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.

但是,这样做对于最后版本的PHP来说增加的负担很小,以致在大多数情况下,结论是这并不重要.

However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.

因此对于表演人员:请使用单引号.对于我喜欢让我的代码可读的人",正如Flavius Stef所指出的那样,双引号的可读性要好得多.

So for the performance people: use single quotes. For the "i like my code readable"-people: double quotes are a lot better for the legibility, as Flavius Stef already pointed out.

不过,有一件事-如果您要在字符串中使用单美元而不包含变量,请确保使用单引号! ( http://www.weberdev.com/get_example-3750.html 指出,解析这些字符串将花费4倍以上的时间

One thing though - If you are going to use a a single dollar in your string without a variable, use single quotes for sure! (http://www.weberdev.com/get_example-3750.html points out that it will take 4 times longer to parse those strings)

这篇关于变量串联的单引号还是双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 20:24