php code

PHP: str_replace array VS str_replace single

Results are quit predictable. Obviously, that as a rule its better to use one function call instead of few. And this case is not exception. But I was curious how big is this difference so I wrote small test.

Test machine:

  • Intel(R) Core(TM) i7-3740QM CPU @ 2.70GHz
  • OSX, Mavericks
  • only 1 tread for server
  • PHP 5.5.17
  • memory limit: 1024M

Iterations for each test:1000000
Count of replaces: 4

  1. //str_replace array
  2. $searchReplace = array(
  3.     's1'     => 'replace1',
  4.     's2'     => 'replace2',
  5.     's3'     => 'replacestring3',
  6.     's4'     => 'test4',
  7. );
  8. str_replace(array_keys($searchReplace),array_values($searchReplace),$str);
  9. /* ############################################ */
  10. //str_replace single
  11. str_replace('s1','replace1',$str);
  12. str_replace('s2','replace2',$str);
  13. str_replace('s3','replacestring3',$str);
  14. str_replace('s4','test4',$str);
//str_replace array 
$searchReplace = array(
    's1'     => 'replace1',
    's2'     => 'replace2',
    's3'     => 'replacestring3',
    's4'     => 'test4',
);
str_replace(array_keys($searchReplace),array_values($searchReplace),$str);
/* ############################################ */
//str_replace single
str_replace('s1','replace1',$str);
str_replace('s2','replace2',$str);
str_replace('s3','replacestring3',$str);
str_replace('s4','test4',$str);

And test results

strlen:               67
str_replace array: 3.4796
str_replace single:   4.7993

strlen:               127
str_replace array: 3.5595
str_replace single:   4.9773

strlen:               254
str_replace array: 4.5496
str_replace single:   5.9848

strlen:               508
str_replace array: 5.2974
str_replace single:   6.772

strlen:               1016
str_replace array: 6.7376
str_replace single:   7.9825

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterEmail this to someoneShare on LinkedIn

Aboutalex

Вэб-программист. Занимаюсь разработкой cервисов, написанием API, вэб-приложений. Интересна разработка приложений для высоконагруженных систем, анализ данных..

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

8 − два =