6

文字列を反復処理して文字列内のバイト数をstrlen実際にカウントしますか、それともインデックスから既に計算された文字列の長さの値を単純に返しますか?

私の質問の理由は、速度に敏感なスクリプト用に非常に長い文字列の事前計算された値をstrlen保存するか、関数を使用してコーディング時間を節約するかを選択できるためです。

strlenしかし、私はそれに大きく依存する傾向があるので、実際にどのように機能するかを知りたいのですが、おそらくこれは良い考えではありませんか?

アップデート

以下の私のベンチマークを参照してください。

4

1 に答える 1

7

それをねじ込み、私はベンチマークを行いました:

<?php
$shortstring='hello';

$longstring='long';
for($run=0;$run<100000;$run++)
    $longstring.='dsffghdgfhdsda'.rand(1000,2000);

$time=microtime(true);
for($run=0;$run<100000000;$run++)
    $temp=strlen($shortstring);
$time=microtime(true)-$time;

echo "strlen on short string took $time seconds\n";

$time=microtime(true);
for($run=0;$run<100000000;$run++)
    $temp2=strlen($longstring);
$time=microtime(true)-$time;

echo "strlen on long string took $time seconds\n";

結果

strlen on short string took 12.508891820908 seconds
strlen on long string took 11.897696971893 seconds

明らかに文字列を反復処理しませんが、事前にインデックス付けされた値を返します。速度に違いはありません。

于 2013-03-02T07:04:27.247 に答える