Skip to content
This repository has been archived by the owner on Jun 29, 2022. It is now read-only.

magnetikonline/php-string-concatenate-benchmark

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 

Repository files navigation

PHP string concatenation benchmarks

A quick and dirty (and possibly incorrect - pull requests appreciated!) test to see what is faster/leaner when joining strings in PHP:

  • method01.php: create an empty string and simply keep adding strings onto it.
  • method02.php: create an empty array, keep appending strings then implode() at the end.

Strings added are random sequences of ASCII A-Z characters to hopefully defeat any skewing introduced by PHP's (very excellent) implementation of string interning.

Tests

Running on an Intel(R) Core(TM) i5-2500 CPU @ 3.30GHz - (of course cores doesn't matter here, PHP is single threaded).

$ php -v

PHP 5.5.10 (cli) (built: Mar  9 2014 12:27:59)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

method01.php

$ time php -d memory_limit=512M method01.php
Memory use: 21000280 bytes

real    0m6.798s
user    0m6.764s
sys     0m0.028s

method02.php

$ time php -d memory_limit=512M method02.php
Memory use: 21000304 bytes

real    0m7.093s
user    0m6.956s
sys     0m0.096s

Conclusion

What does this all mean? Honestly very little:

  • PHP string concatenation is implemented fast, very fast.
  • Yes, method01.php proves to be faster and with a tiny memory saving, but running 1000000(!) passes to produce any real amount of difference this isn't something you would ever do in the lifecycle of a real world PHP web request anyway.
  • Don't bother with creating arrays and using implode() at the conclusion for the sole aim of improving speed. Obviously if concatenation logic can be better written using an array (e.g. backtracking/modifying string hunks as you move along) then do so.
  • Concat a string or use arrays, it don't matter - worry about more important things.
  • Anyway, you're probably getting confused with early .NET framework versions, it's rubbish memory allocation and the need for a StringBuilder() class.

Fin.

About

Trival PHP string concatenation method benchmarks, proving that your time is better spent elsewhere.

Resources

License

Stars

Watchers

Forks

Languages