对于单值检查,首选两者,为什么?
$string == 'The quick brown fox jumps over the lazy dog';
if(strpos($string, 'fox') !== false){
// do the routine
}
# versus
if(preg_match('/fox/i', $string)){
// do the routine
}
我宁愿选择strpos
over preg_match
,因为正则表达式通常更昂贵。
根据官方的php文档preg_match
:
preg_match()
如果只想检查一个字符串是否包含在另一个字符串中,请不要使用。使用
strpos()
或strstr()
代替,因为它们会更快。
如有疑问,请进行基准测试!
显然,我们可以提出一个更好的基准测试,但是只是为了证明随着它开始扩大规模,strpos()
它会更快一些。(这里快了将近2倍)
编辑我后来注意到正则表达式不区分大小写。当再次进行stripos()
比较以进行更公平的比较时,结果为11到15,因此差距缩小了,但preg_match()
仍然慢得多。
$str = "the quick brown fox";
$start1 = time();
for ($i = 0; $i<10000000; $i++)
{
if (strpos($str, 'fox') !== false)
{
//
}
}
$end1 = time();
echo $end1 - $start1 . "\n";
$start2 = time();
for ($i = 0; $i<10000000; $i++)
{
if (preg_match('/fox/i', $str))
{
//
}
}
$end2 = time();
echo $end2 - $start2;
// Results:
strpos() = 8sec
preg_match() = 15sec
// Results both case-insensitive (stripos()):
stripos() = 11sec
preg_match() = 15sec
除非绝对必要,否则请勿使用正则表达式。在像这样的字符串上启动和部署正则表达式引擎所涉及的开销类似于使用手提凿岩机代替常规锤,用钻头代替螺丝刀。
使用正则表达式还会带来更大的误差-字符串不匹配,意外结果等。请坚持使用strpos,除非strpos不够灵活。
如果您已经使用preg_match
并preg_replace
在所有在你的代码的地方,然后再上,并再次使用它。为什么?
-
性能。这些功能增加的大部分开销都在引擎的初始加载时间中,如果您已经付出了这个代价,就值得这样做。
-
可读性。
strpos(...)!==false
虽然速度更快,但是却令人难以置信。它是最丑陋的php构造之一。和
中
的用法确实很笨拙,很难解析,而且很难编辑。==
false
strcontains()
几年前,核心团队感到羞耻,因为他没有为其定义别名。
现在做这件事为时已晚,但是那会很好。
因此,如果有人认为这类事情很重要,则应注意,它在Big O中是一个常数。换句话说,数据库调用,On ^ 2或更差的活动就很重要。在大多数情况下,花时间烦恼这些低级命令是没有意义的。并不是说常量应该被忽略,例如,我重构了捕获图像的代码,因为它一次执行一次,每次花费1秒,然后将其从12秒减少到1秒(使用多重卷曲请求)。关键是内置命令的级别较低,代码结构更为重要。
下面的代码是1000万次调用,“节省”几乎没有。
function prof_flag($str)
{
global $prof_timing, $prof_names;
$prof_timing[] = microtime(true);
$prof_names[] = $str;
}
function prof_print()
{
global $prof_timing, $prof_names;
$size = count($prof_timing);
for($i=0;$i<$size - 1; $i++)
{
echo "<b>{$prof_names[$i]}</b><br>";
echo sprintf(" %f<br>", $prof_timing[$i+1]-$prof_timing[$i]);
}
echo "<b>{$prof_names[$size-1]}</b><br>";
}
$l = 10000000;
$str = "the quick brown fox";
echo "<h3>Ran " .number_format($l,2) ." calls per command </h3>";
prof_flag("Start: stripos");
for ($i = 0; $i<$l; $i++)
if (stripos($str, 'fox') !== false) {}
prof_flag("Start: preg_match");
for ($i = 0; $i<$l; $i++)
if (preg_match('#fox#i', $str) === 1) {}
prof_flag("Finished");
prof_print();
这段代码的唯一价值在于,它显示了一种很酷的方式来记录运行大声笑所需的时间
Ran 10,000,000.00 calls per command
Start: stripos
2.217225
Start: preg_match
3.788667
Start: ==
0.511315
Start: ucwords lol
2.112984
Finished
您可以preg_match
通过编写以下内容来优化上述内容:
preg_match('/(?>fox)/', $str)
这应该更快。
文章标签:php
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!