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


concat php strings; using . operator or double quotes

编辑-我的问题并不严格局限于性能,我还想知道每一个的陷阱,以及是否存在一个应该而不是另一个的情况。

在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语言运算符>字符串

我认为在你开始担心它之前,你需要看看它是否值得思考。我确实考虑过了,写了下面的小脚本并运行它,看看基准是什么样子的。

每绕一圈,我就传球100000次。现在我没有在任何地方打印字符串,所以如果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

连接几乎总是比插值快,但差异很少显著到需要注意的程度。也就是说,我更喜欢串联,因为当(例如(您想将字符串更改为方法或函数调用时,它可以更容易地进行编辑。即,来自:

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

收件人:

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

编辑:当我说"连接几乎总是比插值快"时,我的意思是,我实际上已经对它的许多不同形式进行了基准测试,我不仅仅是猜测或重申别人的帖子。这很容易做到,试试看。

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

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

对于数量不多的字符串,使用哪种方法没有明显差异。