concat php字符串;使用。运算符或双引号

时间:2011-07-27 20:26:17

标签: php string

  

编辑 - 我的问题并非严格限于表现,我也想知道每个问题的陷阱,以及是否有一个应该用于另一个

的情况。

哪个更好用于在PHP中连接字符串?

选项A:使用。运算符来连接字符串

$string1 = "hello ";
$string2 = $string1 . "world !";

选项B:使用双引号

$string1 = "hello ";
$string2 = "$string1 world !";

我意识到事实上两者都会做同样的事情,而在我的个人发展中我更喜欢使用。运营商。 我的问题才出现,因为我已经读过了。运算符强制php重新连接每个新字符串,所以在示例中:

$string1 = "hello ";
$string2 = "world";
$string3 = $string1.$string2." !";

实际上会比

$stirng1 = "hello";
$string2 = "world";
$string3 = "$string1 $string2 !";

参考:PHP Language Operators > Strings

3 个答案:

答案 0 :(得分:4)

连接几乎总是比插值更快,但差异很小,不足以保证关怀。也就是说,我更喜欢连接,因为它允许更简单的编辑(例如)你想要将字符串更改为方法或函数调用。即,来自:

$s1 = 'this ' . $thing . ' with a thing';

要:

$s1 = 'this ' . blarg($thing) . ' with a thing';

编辑:当我说“连接几乎总是比插值更快”时,我的意思是,我实际上已经对它的各种形式进行了基准测试,而且我不只是猜测,或者重申其他人的帖子。这很容易,尝试一下。

答案 1 :(得分:3)

我认为在你开始担心它之前,你需要看看它是否值得考虑。我确实考虑过它,并编写了下面的小脚本并运行它以查看基准测试的内容。

对于每个循环,我进行了100,000次传球。现在我没有在任何地方打印我的字符串,所以如果PHP优化器因此而完成了我的所有工作,那么我道歉。然而,看看这些结果,您会发现每个结果的差异大约为0.00001秒。

在优化除可读性之外的任何内容之前,请使用分析器并查看热点的位置。如果你运行数以千万计的连接,那么你可能会有一个参数。但是对于1000,你仍然在谈论0.01秒的差异。我确信只需优化SQL查询等就可以节省0.01秒以上的时间。

我的证据如下......

这是我跑的:

<?php
for($l = 0; $l < 5; $l++)
  {
    echo "Pass " .$l. ": \n";
    $starta = microtime(1);
    for( $i = 0; $i < 100000; $i++)
      {
    $a = md5(rand());
    $b = md5(rand());
    $c = "$a $b".' Hello';
      }
    $enda = microtime(1);

    $startb = microtime(1);
    for( $i = 0; $i < 100000; $i++)
      {
    $a = md5(rand());
    $b = md5(rand());
    $c = $a . ' ' . $b . ' Hello';
      }
    $endb = microtime(1);


    echo "\tFirst method: " . ($enda - $starta) . "\n";
    echo "\tSecond method: " . ($endb - $startb) . "\n";
  }

结果如下:

Pass 0: 
    First method: 1.3060460090637
    Second method: 1.3552670478821
Pass 1: 
    First method: 1.2648279666901
    Second method: 1.2579910755157
Pass 2: 
    First method: 1.2534148693085
    Second method: 1.2467019557953
Pass 3: 
    First method: 1.2516458034515
    Second method: 1.2479140758514
Pass 4: 
    First method: 1.2541329860687
    Second method: 1.2839770317078

答案 2 :(得分:2)

如果您需要同时将大量字符串放在一起,请考虑implode()

$result = implode('', $array_of_strings);

对于无关紧要的字符串数量,您使用哪种方法没有明显的差异。

相关问题