Wednesday, August 19, 2009
Performance of converting an integer to a string in PHP
We had a discussion at work about the fastest way to convert an integer to a string in PHP. The options were:
- Casting: e.g. (string)$i
- String concatenation: e.g. $i . ''
- String interpolation: e.g. "$i"
- Conversion with strval() e.g. strval($i)
- stringCasting: 0.744 s (e.g. (string)$i)
- stringConcatenation: 0.971 s (e.g. $i . '')
- stringInterpolation: 1.005 s (e.g. "$i")
- strvalConversion: 1.443 s (e.g. strval($i))
- <?
- function timeTrial($functionName, $i) {
- $start = microtime(true);
- $functionName($i);
- $totalTime = sprintf("%0.3f", microtime(true) - $start);
- echo "<h3>$functionName: $totalTime s</h3>";
- flush();
- }
- function stringConcatenation($i) {
- for ($j = 0; $j < $i; ++$j) {
- if ($j . '' === $i . '') {
- echo "This should never happen";
- }
- }
- }
- function strvalConversion($i) {
- for ($j = 0; $j < $i; ++$j) {
- if (strval($j) === strval($i)) {
- echo "This should never happen";
- }
- }
- }
- function stringInterpolation($i) {
- for ($j = 0; $j < $i; ++$j) {
- if ("$j" === "$i") {
- echo "This should never happen";
- }
- }
- }
- function stringCasting($i) {
- for ($j = 0; $j < $i; ++$j) {
- if ((string)$j === (string)$i) {
- echo "This should never happen";
- }
- }
- }
- for ($k = 0; $k < 4; ++$k) {
- $iterations = 1000000;
- foreach (array("stringConcatenation", "strvalConversion", "stringInterpolation", "stringCasting") as $test) {
- timeTrial($test, $iterations);
- }
- }