PHP list+explode VS substr+strpos - what is more efficient?

后端 未结 6 1719
迷失自我
迷失自我 2021-01-04 22:24

Sample text:

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

Task - extract everything before ::

Option 1:

         


        
6条回答
  •  情深已故
    2021-01-04 22:48

    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.

提交回复
热议问题