1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[PHP] preg_replace の処理速度検証

Posted at

検証

半角空白と全角空白(UTF8)を削除する正規表現について、二通りの式を試した。

A
$result = preg_replace('/\x20|\xE3\x80\x80/', "", $_string);
B
$result = preg_replace(array('/\x20/', '/\xE3\x80\x80/', array("", ""), $_string);

結果

Aのほうが、1.25倍くらい速かった。
予想通り。

環境

環境
$ cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 15
model           : 4
model name      : Intel(R) Xeon(TM) CPU 3.60GHz
stepping        : 1
microcode       : 23
cpu MHz         : 3600.000
cache size      : 1024 KB
physical id     : 0
siblings        : 2
core id         : 0
cpu cores       : 1
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 5
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc pebs bts pni dtes64 monitor ds_cpl est tm2 cid cx16 xtpr
bogomips        : 7200.38
clflush size    : 64
cache_alignment : 128
address sizes   : 36 bits physical, 48 bits virtual
power management:

processor       : 1
vendor_id       : GenuineIntel
cpu family      : 15
model           : 4
model name      : Intel(R) Xeon(TM) CPU 3.60GHz
stepping        : 1
microcode       : 23
cpu MHz         : 3600.000
cache size      : 1024 KB
physical id     : 0
siblings        : 2
core id         : 0
cpu cores       : 1
apicid          : 1
initial apicid  : 1
fpu             : yes
fpu_exception   : yes
cpuid level     : 5
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc pebs bts pni dtes64 monitor ds_cpl est tm2 cid cx16 xtpr
bogomips        : 7200.38
clflush size    : 64
cache_alignment : 128
address sizes   : 36 bits physical, 48 bits virtual
power management:


$ cat /etc/redhat-release
CentOS release 6.6 (Final)

$ php -v
PHP 5.6.6 (cli) (built: Feb 19 2015 10:30:11)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2015, by Zend Technologies

余談

最初、

A
$result = preg_replace('/(\x20|\xE3\x80\x80)/', "", $_string);

というふうに、Aのほうでグルーピングした正規表現を使っていて
Bのほうが、1.2倍くらい速い結果となってしまった。

これはたぶん、マッチした文字列をどこかに一時保存する処理が働いたからだと推察してます。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?