2012-03-05 27 views
1

对于函数更快的字符串preg_match()或stripos()来执行不敏感的大小写搜索?preg_match()或stripos()?

<?php 

$string = "This is test string";  
$result = preg_match('/test/i', $string); 

OR 

$result = stripos($string, 'test') !== false; 
?> 
+1

如何标杆它为您的特定用例? – deceze 2012-03-05 05:32:14

+0

'stripos'的速度更快,但'preg_match'要复杂得多。 – Bjoern 2012-03-05 05:33:26

+0

如果你不使用正则表达式,那么不要使用'preg_xxx'。 – 2012-03-05 05:41:58

回答

4

这是我的经验,stripos更快。

+1

刚刚使用您的字符串进行了测试并搜索......在这种情况下,显示stripos约快2.3倍,以给出两者之间速度差异的示例。 – 2012-03-05 05:36:05

1

如果你不需要实际匹配一个复杂的表达式,或捕捉的东西就用striposstrpos

0

strpos更快,因为这个功能有预定义规则这是什么功能都做的......其中的preg_match功能我们必须从我们身边经过的逻辑......所以在这种情况下,首先必须在此基础上

所以吊索是更快地定义规则和工作....

0

对于真正的性能增益我会避免“密集搜索“。

某些高级搜索技术,如使用mysql或sphinx进行索引全文搜索,将为为真正的解决方案,用于“密集搜索”问题。

虽然所有这些可以忽略不计的比较这些已经效率低下功能涉及全面扫描的数据将无济于事。

如果你坚持使用这些 - 没有性能是你的关注。因此 - 不要浪费任何时间进行比较。

0

stripos是缓慢的,优于使用strtolowerstrpos

<?php 

function loop() 
{ 
    $str_50 = str_repeat('a', 50).str_repeat('b', 50); 
    $str_100 = str_repeat('a', 100).str_repeat('b', 100); 
    $str_500 = str_repeat('a', 250).str_repeat('b', 250); 
    $str_1k = str_repeat('a', 1024).str_repeat('b', 1024); 
    $str_10k = str_repeat('a', 10240).str_repeat('b', 1024); 
    $str_100k = str_repeat('a', 102400).str_repeat('b', 1024); 
    $needle = 'b'; 

    header("Content-Type: text/plain"); 

    echo str_replace(',', "\t", 'count,strpos,preg,stripos,preg i,strpos(tolower)').PHP_EOL; 

    foreach(array($str_50, $str_100, $str_500, $str_1k, $str_10k, $str_100k) as $str) 
    { 
    echo strlen($str); 
    $start = mt(); 
    for($i = 0; $i < 25000; $i++) $j = strpos($str, $needle); // strpos 
    echo "\t".mt($start); 

    $regex = '!'.$needle.'!'; 
    $start = mt(); 
    for($i = 0; $i < 25000; $i++) $j = preg_match($regex, $str); // preg 
    echo "\t".mt($start); 

    $start = mt(); 
    for($i = 0; $i < 25000; $i++) $j = stripos($str, $needle); // stripos 
    echo "\t".mt($start); 

    $regex = '!'.$needle.'!i'; 
    $start = mt(); 
    for($i = 0; $i < 25000; $i++) $j = preg_match($regex, $str); // preg i 
    echo "\t".mt($start); 

    $str = strtolower($str); 
    $start = mt(); 
    for($i = 0; $i < 25000; $i++) $j = strpos($str, $needle); // strtolower strpos 
    echo "\t".mt($start); 

    echo PHP_EOL; 
    } 
    echo PHP_EOL; 
} 


function mt($start = null) 
{ 
    if($start === null) 
    return microtime(true); 
    return number_format(microtime(true)-$start, 4); 
} 


loop(); 

结果在几秒钟内

count  strpos  preg  stripos  preg i  strpos(tolower) 
100  0.0243  0.0395  0.0878  0.0339  0.0094 
200  0.0100  0.0334  0.1636  0.0354  0.0103 
500  0.0114  0.0368  0.4211  0.0415  0.0115 
2048  0.0174  0.0556  1.5797  0.0653  0.0171 
11264  0.0896  0.2727  8.7098  0.3531  0.0890 
103424  0.8218  2.4429  79.7007  3.2986  0.8190