Uses an array faster than multiple statements?

I am curious. Is there any better performance with this:

$value  = preg_replace( array('/_{1,}/', '/-{2,}/'), array('_', '-'), $value);

than this:

$value  = preg_replace('/_{1,}/', '_', $value);
$value  = preg_replace('/-{2,}/', '-', $value);

This is just a very simple example.

+5
source share
5 answers

Like my test code:

$value = 'dfkjgnnfdjgnjnfdkgn dnf gnjknkxvjn jkngjsrgn';
$value1 = 'dfkjgnnfdjgnjnfdkgn dnf gnjknkxvjn jkngjsrgn';

$start = microtime(true);
for ($i = 0; $i < 1000000; $i++)
$value  = preg_replace( array('/_{1,}/', '/-{2,}/'), array('_', '-'), $value);
echo microtime(true) - $start.'<br>';

$start1 = microtime(true);
for ($i = 0; $i < 1000000; $i++){
    $value1  = preg_replace('/_{1,}/', '_', $value1);
    $value1  = preg_replace('/-{2,}/', '-', $value1);
}
echo microtime(true) - $start1;

+1,4254899024963

+1,2811040878296

+3
source

Using the microtime () test method that PLB mentioned in the comments, you look at the performance difference by 0.3 seconds. The second example is "faster."

+2
source

, , - :

$value  = '1_2__3___4____5_____6______1-2--3---4----5-----6------';

$s_1    = microtime(true);
    for ($i = 0; $i < 1000000; ++$i) {
        $r_1    = preg_replace( array('/_{2,}/', '/-{2,}/'), array('_', '-'), $value);
    }
$e_1    = microtime(true);

$s_2    = microtime(true);
    for ($i = 0; $i < 1000000; ++$i) {
        $r_2    = preg_replace('/_{2,}/', '_', $value);
        $r_2    = preg_replace('/-{2,}/', '-', $r_2);
    }
$e_2    = microtime(true);

print $r_1;
print $r_2;
print $e_1 - $s_1;
print $e_2 - $s_2;

:

+3,69554805756

3,2879319191

, - - , - . , "" . , , .

+1

, , , , .

+2,0891699790955

+2,2491400241852


+3,2192239761353

+3,4498269557953


PHP: 5.4.9

: Ubuntu x64

: i7-3630QM

0

. MacOS , insertnamehere:

// Arrays
1.8200218677521

// Individual statements
2.4083371162415

. , , . , ?

$find = array('/_{2,}/', '/-{2,}/');
$replace = array('_', '-');

$s_3    = microtime(true);
    for ($i = 0; $i < 1000000; ++$i) {
        $r_1    = preg_replace( $find, $replace, $value);
    }
$e_3    = microtime(true);
1.7364799976349  // Arrays (created)
2.4450128078461  // Individual statements
1.5605390071869  // Arrays (referenced)

, . .

It is important to note that if you simply reload the page several times, the coincidence rates of the two arrays tend to converge until there is a slight difference. Presumably, this is PHP caching of a compiled script - a little editing and saving it again gives more divergent values.

So, there is another benchmark for production environment - how do the values ​​change over time in a real scenario?

0
source

All Articles