文字連結の処理速度

2009年 7月 13日

具体的に文字列連結はHTMLタグを出力するために使用することが多く処理の速度は気になるところだ。

文字列を加算していくのは、計算の途中で、abcde、abcdeabcde、abcdeabcdeabcdeという文字列オブジェクトがその都度生成されていくのでメモリにやさしくない。巨大な文字列の連結にはjoinを使ったほうが良い。数が大きくなると速度に差が出てくる。

引用元: 最速インターフェース研究会 :: 実践JavaScriptリファクタリング.

PHPの結果が気になったのでこちらの記事を参考に(若干コードを変更)して実験してみたところ、連結の方法が最も速いと言う結果になった。元記事のサンプルコードでも統計的に同じ結果(DoS攻撃してスミマセン)なので、PHPのバージョンや環境の明記が必要だと思った。尚今回の環境はMac OS X 10.5.7のPHP 5.2.8 (cli) (built: Feb 5 2009 21:21:13) をApache/2.2.11 (Unix) (Server built: Feb 3 2009 01:54:45)のモジュールとして利用している。

特にIEで顕著なのだが、JavaScriptはappendChild関数を使うより文字連結したタグをinnerHTML関数で差し込む方が速いということも同種の問題が起因しているのだろうか。これらの問題は、コンピュータ上のWebkitやChromeであれば意識する必要もあまりないのかもしれないが、iPhoneなど非力ハード上ではまだまだ注意すべき問題だろう。

screen-capture-11

// 追記編
$time1 = getmicrotime();
$str = null;
for($n = 0; $n < $count; $n++){
    $str.= $str1;
    $str.= $str2;
    $str.= $str3;
}
$time1 = getmicrotime() - $time1;
 
// 連結編
$time2 = getmicrotime();
$str = null;
for($n = 0; $n < $count; $n++){
    $str.= $str1.$str2.$str3;
}
$time2 = getmicrotime() - $time2;
 
// 非連結編
$time3 = getmicrotime();
$str = null;
for($n = 0; $n < $count; $n++){
    $str.= "$str1$str2$str3";
}
$time3 = getmicrotime() - $time3;
 
// 配列編1
$time4 = getmicrotime();
$arr = array();
for($n = 0; $n < $count; $n++){
  array_push($arr, $str1, $str2, $str3);
}
$str = implode('', $arr);
$time4 = getmicrotime() - $time4;
 
// 配列編2
$time5 = getmicrotime();
$arr = array();
for($n = 0; $n < $count; $n++){
  $arr[] = $str1;
  $arr[] = $str2;
  $arr[] = $str3;
}
$str = implode('', $arr);
$time5 = getmicrotime() - $time5;