String Camels Slow Performance

So, I have this piece of code in a static method Camelize

return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));

It is just a camel.

I have about 211 thousand records, closed loop iteration. These entries contain a few words that I need for a camel, the longest word can be about 10 characters, simple peasy, but with some xhprof tests, I came to the conclusion that camelize is not a good idea if you need speed.

XHProf with camelize : 313,866,303 microseconds (~ 5 minutes)

  • 19,268,795 calls
  • On Wall time 228 658 500
  • ICpu: 81.3%

XHProf without camelize : 55,099,811 microseconds (<1min)

The purpose of this script is to set values ​​for class properties.

The property may be protected $myVarthat is camelized.

underscore ( ) ( ). my_var => foo

, camelize, - $this->$camelizedProperty = $value

, , - , , 4 , , , , .

UPDATE

microtime, , ...

:

  • strtr(ucwords(strtr($word, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''))
  • lcfirst(str_replace(" ", "", ucwords(strtr($word, "_-", " "))))
  • str_replace(" ", "", ucwords(strtr($word, "_-", " ")))

~ 100 :

  • 0,0011
  • 0,0002
  • 0,0002

@RST , str_replace 18% , , ( )

20- , xhprof, :

  • 313 (~ 5 )
  • 152 (~ 2,5 )
  • 158 (~ 2,5 )

, lcfirst script ( , ).

, , , , .

+4
1

, , , PHP .

20 :

Method 1 time: 301.143823 
Method 2 time: 54.648126

, , , -, . , 5 ($ runqty) 4 , 20 - .

...

<?php

$input = array();
$input['my_var'] = 'foo';
$input['this.that'] = 'blah';
$input['try\\me'] = 'strange';
$input['some_var_here'] = 'value';
$input['final_cut'] = 'fc99';

set_time_limit(600);

$runqty = 1;

// Method 1
$m1start = microtime(true);
for ($runs = 0; $runs < $runqty; $runs++)
{
  foreach ($input as $word => $val)
  {
    $out = strtr(ucwords(strtr($word, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));
    echo "in: $word out: $out<br>\n";
  }
}
$m1stop = microtime(true);
$m1time = $m1stop - $m1start;
echo "Method 1 time: " . sprintf("%0.6f",$m1time);
echo "<br>\n";

// Method 2
$m2start = microtime(true);
for ($runs = 0; $runs < $runqty; $runs++)
{
  foreach ($input as $word => $val)
  {
    $i=0;
    $len = strlen($word);
    $ucnext = true;
    $out = '';

    while ( $i < $len )
    {
      $char = $word[$i++];
      if ( $char == '_' || $char == '.' || $char == '\\' )
      {
        $ucnext = true;
        if ( $char == '.' )
          $char ='_';
        else
          $char = '';
      }
      else
      {
        if ( $ucnext )
        {
          if ( $char >= 'a' && $char <= 'z' )
            $char = ucfirst($char);
          $ucnext = false;
        }
      }

      $out .= $char;
    }
    echo "in: $word out: $out<br>\n";
  }
}
$m2stop = microtime(true);
$m2time = $m2stop - $m2start;
echo "Method 2 time: " . sprintf("%0.6f",$m2time);
echo "<br>\n";

. , , ucnext false ( true, ).

0

All Articles