PHP list +爆炸VS substr + strpos-效率更高的方法是什么? [英] PHP list+explode VS substr+strpos - what is more efficient?

查看:143
本文介绍了PHP list +爆炸VS substr + strpos-效率更高的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例文字:

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

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

选项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的处理. 解决方案2是否在0.38502216339111秒内完成

测试2: 在0.1990110874176秒内完成了solution1的处理. 解决方案2在0.37402105331421秒内完成了.

测试3: 在0.19801092147827秒内完成了solution1的处理. 解决方案2是否在0.37002205848694秒内完成.

Sample text:

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

Task - extract everything before ::

Option 1:

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

Option 2:

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

Which option is more efficient?

解决方案

I ran a test and seems like the first solution is faster. Here is the code for testing it:

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";

Test 1: Did solution1 in 0.19701099395752 seconds. Did solution2 in 0.38502216339111 seconds.

Test 2: Did solution1 in 0.1990110874176 seconds. Did solution2 in 0.37402105331421 seconds.

Test 3: Did solution1 in 0.19801092147827 seconds. Did solution2 in 0.37002205848694 seconds.

这篇关于PHP list +爆炸VS substr + strpos-效率更高的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆