String manipulation vs Regexps

后端 未结 6 503
轮回少年
轮回少年 2021-01-18 13:45

We are often told that Regexps are slow and should be avoided whenever possible.

However, taking into account the overhead of doing some string manipulation oneself (

6条回答
  •  花落未央
    2021-01-18 14:06

    Regular expressions will never be faster than a hand-made algorithm for a very specific purpose. Worse, in PHP they have to be compiled the first time they're used (a cache is used afterwards).

    However, they are certainly more succinct. Moreover, writing custom algorithms is often slower than regexes because the regular expressions engine are usually implemented in a more low level language, with less overhead in calling functions, etc.

    For instance, preg_replace('/a/', 'b', $string) will almost certainly be faster than looping in PHP through the string. But this is a constant penalty in execution time and sometimes regular expressions, due to backtracking, can have a much worse asymptotic behavior.

    You are strongly encouraged to know how regular expressions are implemented so that you can know when you're writing inefficient ones.

提交回复
热议问题