zoukankan      html  css  js  c++  java
  • str_replace vs preg_replace

    转自:http://benchmarks.ro/2011/02/str_replace-vs-preg_replace/

    事实证明str_replace确实比preg_replace快。

    If you find yourself handling strings and replacing sub-strings within them you want to make sure that you are using the fastest way possible to do it.
    In order to help you we ran tests using an average length string (50k characters) and 100*1000 test runs.
    After running these tests we concluded that str_replace is faster thanpreg_replace when it comes to simple replace rules, these being our results for two separate full test runs:

    Time for str_replace: 2.2866821289062 seconds
    Time for preg_replace: 2.9614992141724 seconds

    Time for str_replace: 2.471617937088 seconds
    Time for preg_replace: 3.2965259552002 seconds

    You can see the code we used for benchmarking below:

    <?php
    
    //Build string to be used
    $max_elements=50000; $max_runs=100;
    
    $test_string='';
    for($i=0;$i<$max_elements;$i++)    $test_string.=chr(rand(32,127));
    
    function test_str_replace()
    {
    global $test_string,$max_runs;
    for($i=0;$i<$max_runs;$i++)    $test_string=str_replace(' ',' ',$test_string);
    }
    
    function test_preg_replace()
    {
    global $test_string,$max_runs;
    for($i=0;$i<$max_runs;$i++)    $test_string=preg_replace("/[ ]/",' ',$test_string);
    }
    
    $time = microtime(true);
    for($i=0;$i<$max_runs;$i++) test_str_replace();
    $time = microtime(true) - $time;
    echo "Time for str_replace: {$time} seconds<br>
    ";
    
    $time = microtime(true);
    for($i=0;$i<$max_runs;$i++) test_preg_replace();
    $time = microtime(true) - $time;
    echo "Time for preg_replace: {$time} seconds<br>
    ";
    
    ?>
  • 相关阅读:
    一个面试问题的答案总结
    全局变量与局部变量的特点
    浮点数类型在内存当中是如何存储的
    常用的几种调用约定
    裸函数
    安卓活动的启动模式
    安卓的生命周期
    android中的内部存储与外部存储
    堆栈图学习汇编结束篇最后一个堆栈图的练习
    Android内部存储与外部存储的文件操作类
  • 原文地址:https://www.cnblogs.com/wangkongming/p/4534047.html
Copyright © 2011-2022 走看看