示例文本:

$text = 'Administration\Controller\UserController::Save';

任务-提取::之前的所有内容

选项1:
list($module) = explode('::',$text);

选项2:
$module = substr($text, 0, strpos($text, '::');

哪个选项更有效?

最佳答案

我进行了测试,似乎第一个解决方案更快。
这是测试它的代码:

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

function solution1($text)
{
    for($i = 0; $i < 10000; $i++)
        list($module) = explode('::',$text);
}

function solution2($text)
{
    for($i = 0; $i < 10000; $i++)
        $module = substr($text, 0, strpos($text, '::'));
}

$text = 'Administration\Controller\UserController::Save';

$time_start = microtime_float();

solution1($text);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did solution1 in $time seconds.\n";

$time_start = microtime_float();

solution2($text);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did solution2 in $time seconds.\n";

测试1:
在0.19701099395752秒内完成了solution1的处理。
在0.38502216339111秒内完成了solution2的处理。

测试2:
在0.1990110874176秒内完成了solution1的处理。
在0.37402105331421秒内完成了solution2的处理。

测试3:
在0.19801092147827秒内完成了solution1的处理。
在0.37002205848694秒内完成了solution2的处理。

10-05 20:28
查看更多