给定一个变量$txt,它的性能最好:
$a = (int)$txt;
$b = (int)substr($txt, -2);
您可以使用这样的脚本来衡量不同替代方案的性能:
<?php
$txt = "01-02";
$test_count = 4000000;
// SUBSTR -2
$time_start = microtime(true);
for ($x = 0; $x <= $test_count; $x++) {
$a = (int)$txt; // numeric conversion ignores second part of string.
$b = (int)substr($txt, -2);
}
$duration = round((microtime(true) - $time_start) * 1000);
echo "substr(s,-2): {$a} {$b}, process time: {$duration}ms <br />";
// SUBSTR 3, 2
$time_start = microtime(true);
for ($x = 0; $x <= $test_count; $x++) {
$a = (int)$txt; // numeric conversion ignores second part of string.
$b = (int)substr($txt, 3, 2);
}
$duration = round((microtime(true) - $time_start) * 1000);
echo "substr(s,3,2): {$a} {$b}, process time: {$duration}ms <br />";
// STR_SPLIT
$time_start = microtime(true);
for ($x = 0; $x <= $test_count; $x++) {
$arr = str_split($txt, 3);
$a = (int)$arr[0]; // the ending hyphen does not break the numeric conversion
$b = (int)$arr[1];
}
$duration = round((microtime(true) - $time_start) * 1000);
echo "str_split(s,3): {$a} {$b}, process time: {$duration}ms <br />";
// EXPLODE
$time_start = microtime(true);
for ($x = 0; $x <= $test_count; $x++) {
$arr = explode('-', $txt);
$a = (int)$arr[0];
$b = (int)$arr[1];
}
$duration = round((microtime(true) - $time_start) * 1000);
echo "explode('-',s): {$a} {$b}, process time: {$duration}ms <br />";
// PREG_MATCH
$time_start = microtime(true);
for ($x = 0; $x <= $test_count; $x++) {
preg_match('/(..).(..)/', $txt, $arr);
$a = (int)$arr[1];
$b = (int)$arr[2];
}
$duration = round((microtime(true) - $time_start) * 1000);
echo "preg_match('/(..).(..)/',s): {$a} {$b}, process time: {$duration}ms <br />";
?>
当我在 PhpFiddle Lite 上运行时,我得到了这样的结果:
substr(s,-2): 1 2, process time: 851ms
substr(s,3,2): 1 2, process time: 971ms
str_split(s,3): 1 2, process time: 1568ms
explode('-',s): 1 2, process time: 1670ms
preg_match('/(..).(..)/',s): 1 2, process time: 3328ms
substr 与 (s, -2) 或 (s, 3, 2) 作为参数的性能几乎相同,前提是您只使用一个调用。有时第二个版本会成为赢家。 str_split 和 explode 表现相当接近,但不是很好,preg_match 显然更松。结果取决于服务器负载,因此您应该在自己的设置上尝试此操作。但可以肯定的是,正则表达式的负载很重。当您可以使用其他字符串函数完成工作时,请避免使用它们。
当我意识到您可以立即将原始字符串转换为 int 时,我编辑了我的答案,这将忽略它无法解析的部分。这实际上意味着您可以将第一部分作为数字获取,而无需调用任何字符串函数。这是让substr 成为绝对赢家的决定性因素!