> 境目を探すのに長さ1文字から「変換しても大丈夫?」をキチキチと繰り返すのはかなり時間の無駄なのですが,ここは安全性重視です.
やはりこれがどうも気になっていたので,function autocut998_sub()を二分法的なアルゴリズムに変えました.
function autocut998_sub($line, $max_line_length, $encode)
{
if (($linelength = mb_strwidth($line)) == 0) return '';
if (strlen(mb_convert_encoding($line, $encode, 'UTF-8')) <= $max_line_length) return $line;
$offsetA = 0; $offsetB = $linelength;
while (1) {
$offsetC = (int)(($offsetA + $offsetB) / 2);
if (($offsetC == $offsetA) || ($offsetC == $offsetB)) {
$line = mb_substr($line, 0, $offsetC)."\n".autocut998_sub(mb_substr($line, $offsetC), $max_line_length, $encode);
return $line;
}
$newlinelength = strlen(mb_convert_encoding(mb_substr($line, 0, $offsetC), $encode, 'UTF-8'));
if ($newlinelength >= $max_line_length) $offsetB = $offsetC;
else $offsetA = $offsetC;
}
}
これで,サンプルの文字列データをmb_convert_encoding()する回数が,元のキチキチと頑張る方法では1971回も呼ばれていたのに対して,36回に激減しました.再帰呼び出しの回数は変わらないのでメモリの消費量は変化ありません.純粋に計算回数だけの減少ですが,かなり気持ちがスッキリしました.