为了账号安全,请及时绑定邮箱和手机立即绑定

在php5中使用内联字符串与串联的速度差异?

在php5中使用内联字符串与串联的速度差异?

PHP
慕村225694 2019-08-02 15:32:52
在php5中使用内联字符串与串联的速度差异?(假设php5)考虑<?php     $foo = 'some words';     //case 1     print "these are $foo";     //case 2     print "these are {$foo}";     //case 3     print 'these are ' . $foo;?>1和2之间有很大差异吗?如果没有,那么在1/2和3之间呢?
查看完整描述

3 回答

?
米脂

TA贡献1836条经验 获得超3个赞

好吧,就像所有“现实生活中可能更快”的问题一样,你无法击败现实生活中的考验。

function timeFunc($function, $runs){
  $times = array();

  for ($i = 0; $i < $runs; $i++)
  {
    $time = microtime();
    call_user_func($function);
    $times[$i] = microtime() - $time;
  }

  return array_sum($times) / $runs;}function Method1(){ 
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are $foo";}function Method2(){
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are {$foo}";}function Method3()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are " . $foo;}print timeFunc('Method1', 10) . "\n";print timeFunc('Method2', 10) . "\n";print timeFunc('Method3', 10) . "\n";

给它几个运行页面,然后......

0.0035568

0.0035388

0.0025394

因此,正如预期的那样,插值几乎相同(噪声水平差异,可能是由于插值引擎需要处理的额外字符)。直线连接约为速度的66%,这并不是很大的震撼。插值解析器将查找,无需执行任何操作,然后使用简单的内部字符串concat完成。即使concat很昂贵,插值器仍然必须这样做,解析变量并修剪/复制原始字符串的所有工作之后

Somnath的更新:

我将Method4()添加到上面的实时逻辑中。

function Method4()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = 'these are ' . $foo;}print timeFunc('Method4', 10) . "\n";Results were:0.00147390.00155740.00119550.001169

当你只是声明一个字符串而不需要解析那个字符串时,为什么要混淆PHP调试器来解析。我希望你明白我的观点。


查看完整回答
反对 回复 2019-08-02
  • 3 回答
  • 0 关注
  • 269 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信