note 88967 added to function.strlen
| From: | Anonymous at osu1 dot php dot net | Date: | Mon, 16 Feb 2009 05:51:12 +0000 |
| Subject: | note 88967 added to function.strlen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-150716@lists.php.net to get a copy of this message | ||
simple speed test for UTF-8 strings:
<?php
header("Content-type: text/html; charset=UTF-8");
ini_set('mbstring.internal_encoding', 'UTF-8');
?><pre><?
function utf8_strlen($s) {
$c = strlen($s); $l = 0;
for ($i = 0; $i < $c; ++$i) if ((ord($s[$i]) & 0xC0) != 0x80) ++$l;
return $l;
}
function utf0_strlen($s) {
$l = 0; $i = 0;
while ($n = ord($s[$i++])) if (($n & 0xC0) != 0x80) ++$l;
return $l;
}
function utfs_strlen($s) {
$c = strlen($s);
$l = 0;
for($i = 0; $i < $c; $i++) {
$v = ord($s[$i]);
if($v > 127) {
if($v >= 192 && $v <= 223) ++$i;
elseif($v >= 224 && $v <= 239) $i += 2;
elseif($v >= 240 && $v <= 247) $i += 3;
else die('Not a UTF-8 compatible string');
}
++$l;
}
return $l;
}
function spl_strlen($s) {
return count(preg_split("//u", $s)) - 2;
}
function dcd_strlen($s) {
return strlen(utf8_decode($s));
}
function preg_strlen($s) {
return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $s, $d);
}
$src = '=123! !Ñ"в#$%&\'()*+,â./:;<=>?@[\]^_`{|}~'.
' йÑÑкенгÑÑзÑ
ÑÑÑвапÑолджÑÑбÑ'.chr(0).'Ñ';
$tc = 10000; //test count
$l = mb_strlen($src, 'UTF-8'); //real testing string length
$lst = array('strlen', 'mb_strlen', 'dcd_strlen',
'preg_strlen', 'utfs_strlen', 'utf8_strlen',
'utf0_strlen', 'spl_strlen'); // list of functions
foreach ($lst as $f) {
$t = microtime(1);
for($i = 0; $i < $tc; $i++) $f($src);
$t = microtime(1) - $t;
printf("%14s : %0.6f : %03u%s\n",
$f, $t, $q = $f($src), $q != $l ? ' - failed!' : '');
}
?></pre>
main results:
strlen : 0.009419 : 112 failed!
mb_strlen : 0.016377 : 075
dcd_strlen : 0.063055 : 075
preg_strlen : 1.106809 : 075
utfs_strlen : 1.701586 : 075
utf8_strlen : 2.321344 : 075
utf0_strlen : 2.578518 : 073 failed!
spl_strlen : 3.789029 : 075
----
Server IP: 91.196.196.205
Probable Submitter: 82.193.115.211
----
Manual Page -- http://www.php.net/manual/en/function.strlen.php
Edit -- https://master.php.net/note/edit/88967
Del: integrated -- https://master.php.net/note/delete/88967/integrated
Del: useless -- https://master.php.net/note/delete/88967/useless
Del: bad code -- https://master.php.net/note/delete/88967/bad+code
Del: spam -- https://master.php.net/note/delete/88967/spam
Del: non-english -- https://master.php.net/note/delete/88967/non-english
Del: in docs -- https://master.php.net/note/delete/88967/in+docs
Del: other reasons-- https://master.php.net/note/delete/88967
Reject -- https://master.php.net/note/reject/88967
Search -- https://master.php.net/manage/user-notes.php