简体   繁体   English

PHP什么是更快的{$ code}或。$ code?

[英]PHP what is faster {$code} or .$code?

I dont know how i can test it. 我不知道该如何测试。

What is faster in PHP: 什么是更快的PHP:

$test = "Text {$code}";

or 要么

$test = "Text ".$code;

?

In the real world, you will never notice any difference, so don't stress about it :) 在现实世界中,您永远不会注意到任何差异,所以不要着急:)

It's unlikely you will experience any noticeable speed problems with either of your options, but let me explain the differences anyway and what the quickest solution would be. 您选择这两种方法都不太可能遇到任何明显的速度问题,但无论如何,让我解释一下两者之间的差异以及最快的解决方案是什么。

When you use double quotes "like this" php will attempt to evaluate any text within the quotes, which is why you can use {$code} within it, you could of course also miss out the curly brackets and simply write "Text $code" unless there is something more complex than a simple variable being evaluated. 当您使用双引号“ like this”时,php会尝试评估引号内的任何文本,这就是为什么您可以在其中使用{$ code}的原因,您当然也可能会忽略大括号,而只写“ Text $ code” ”,除非比简单的变量要复杂的多。

Your second example I expect would be marginally slower (I don't have evidence of this, but I suppose we could write a simple test for it if required). 我希望您的第二个示例稍慢一些(我没有证据,但是我想如果需要的话,我们可以为此编写一个简单的测试)。 As it is first attempting to evaluate the string, THEN concatenating a variable to the string, this is a separate operation. 在第一次尝试评估字符串时,然后将变量连接到字符串,这是一个单独的操作。

If speed is your real concern, then use single quotes. 如果速度是您真正关心的问题,请使用单引号。 The contents of these will never be evaluated, so you can simply take the text string and concatenate the variable. 这些内容永远都不会被求值,因此您可以简单地使用文本字符串并连接变量。

Like this: 像这样:

$test = 'Text ' . $code

Your first option is the fastest: 您的第一个选择是最快的:

Benchmarks run against PHP 5.2 and 5.3 show that parsing double-quoted strings with interpolation is no slower (and often faster) than single- quoted strings using concatenation. 针对PHP 5.2和5.3进行的基准测试表明,使用插值法对双引号字符串进行解析不会比使用串联的单引号字符串慢(并且通常会更快)。 When simple strings with no variables in them are used, the performance is clearly better with double-quoted strings due to implementation details in the engine. 当使用其中没有变量的简单字符串时,由于引擎中的实现细节,使用双引号字符串的性能明显更好。

Reference here 这里参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM