When printing strings, which of these will execute fastest? And why? And can you prove it...?

<?php

$fname = 'Jake';
$lname = 'Mahoney';

// first method, using printf:
for($i = 0; $i < 10000; $i++) {
	printf("His name is %s %s %d.", $fname, $lname, $i);
}

// Second method, using string concatenation (with double quotes):
for($i = 0; $i < 10000; $i++) {
	print("His name is " . $fname . " " . $lname . " " . $i . ".");
}

// third method, using string concatenation, using single-quoted strings:
for($i = 0; $i < 10000; $i++) {
	print('His name is ' . $fname . ' ' . $lname . ' ' . $i . '.');
}
?>

    i would guess that printf would be the fastest since it's probably a straight implementation of the original c code. echo and print would have to parse the line to make it printf compliant anyway.

    have you not run tests?

      In fact, I did run tests. Several tests (many, many times each), after reading some bozo's article (I forget the source, but he's full of it, anyway) regarding misuse of the printf() function in PHP and how using print, string concatenation, is so much faster.

      My tests have shown only a very, very neglible difference between using printf() and print(), with the slight advantage going to the printf() function.

      Thanks for your feedback...

        Here's a couple more to try:

        for($i = 0; $i < 10000; $i++) {
            echo 'His name is ' . $fname . ' ' . $lname . ' ' . $i . '.';
        }
        
        for($i = 0; $i < 10000; $i++) {
            echo 'His name is ' , $fname , ' ' , $lname , ' ' , $i , '.';
        }
        

        The sample is of course too short and variable-dense to make sense trying heredocs or escaping out of the PHP parser entirely.

          echo's better than printf. I didn't really much tested it, just believe it.

          single quotes faster than double. Also not much testing, but logic says it is.

          echoing dot-concatenated string faster than echoing a comma-separated list of strings - that's for sure, and difference is obvious. They differ dozens percent, if not times.

            Well, here's a few runs I tried. I timed $i=0..99,999 iterations of the loop for each test, then continued on and did another 100,000 iterations of each in the opposite order (just in case system reallocations started to bog things down). As it happened, even though I was using a pretty limited system at the time, there were plenty of resources available that the effect didn't really matter.

            I ran it from the command-line, redirecting the output to a file. The Zend Optimizer was not installed.

            seconds
            18	printf("This man, %s %s, is %s today", $fname, $lname, $i);
            
            15	printf('This man, %s %s, is %s today', $fname, $lname, $i);
            
            19	print("This man, $fname $lname, is $i today");
            
            10	print("This man, ".$fname." ".$lname.", is ".$i." today");
            
            11	print('This man, '.$fname.' '.$lname.', is '.$i.' today');
            
            18	echo("This man, $fname $lname, is $i today");
            
            10	echo "This man, ".$fname." ".$lname.", is ".$i." today" ;
            
            10	echo 'This man, '.$fname.' '.$lname.', is '.$i.' today' ;
            
            11	echo 'This man, ',$fname,' ',$lname,', is ',$i,' today' ;
            
            11	?>This man, <?php echo $fname?> <?php echo $lname?>, is <?php echo $i?> today<?php
            

            The real slowdown is variable interpolation; while echo speeds things up nicely. But that's for 200,000 iterations of the loop, so it's generally not a saving worth getting all worked up about: One would probably lose more time worrying about such optimisations than would be gained by implementing them. Unless you're maintaining something like slashdot.org or microsoft.com - and then you'd probably be better off getting a faster machine.

            There are plenty of more significant savings to be had by application of intelligence to program and data design.

              Of course, optimization is rarely worth effort. But once you get used to the better style, your scripts will be a little bit faster, so it's useful to keep in mind, which is better.
              Millisecond here, millisecond there - and all the Internet speeds up a great deal 🙂

                I'm setting up some more tests right now using the echo function with concatenated strings, using both dot-concatenation and comma-concatenation.

                Thanks for your feedback, I'll let you know how thangs turn out...

                  Originally posted by the_Igel
                  But once you get used to the better style, your scripts will be a little bit faster, so it's useful to keep in mind, which is better.

                  Yeah, but the "better style" in this case appears to be ugly as sin. What's the point of saving milliseconds here and there on the server if it means wasting minutes of your time in eye-crossing debugging and maintenance (while the server sits and continues to run in its unmaintained state)?

                  I've always used echo instead of print simply because I couldn't see the point of print's return value - and the line looks cleaner without the (). I'm not going to stop using variable interpolation on the strength of these results, because "printing $this is" a lot easier to read than ?>printing <?php echo $this?> is<?php.

                  Now if the text was significantly longer and the variables made up a smaller portion, then:

                  1. I'd much more likely use ?>dropping out of PHP mode<? when outputting;

                  2. <<<heredocs or multiline literals when assigning a wodge of text to a variable;

                  3. and I certainly wouldn't do half a myriad print() or $var.="" lines the way I see done so distressingly often.

                  Unfortunately, because the information is commercially sensitive, we can't find out just how much this is made moot by products like Zend's Optimizer.

                  "Sits and continues to run?" .... ooh .... that was bad.

                    Okay, folks... my semi, sorta, kinda, somewhat, slightly scientific analysis has been done, yet again.

                    The Objective: try and determine what's the fastest method to generate dynamic strings.

                    Method: Compare 7 different methods of string construction:

                    1: printf();

                    2: print (using double-quoted strings and string concatenation);

                    3: print (using single-quoted strings and string concatenation);

                    4: echo (using single-quoted strings and dot concatenation);

                    5: echo (using single-quoted strings and comma concatenation);

                    6: echo (using double-quoted strings and dot concatenation);

                    7: echo (using double-quoted strings and comma concatenation);

                    Environment: SuSE 7.3 Linux on a 550 MHz PIII w/ 256MB of RAM; Apache 1.3.20 httpd server, PHP 4.0.6 installed as a DSO, Zend Engine v 1.0.6.

                    All tests consisted of 20000 iterations of a loop, where inside the loop, the following line was printed: 'His name is: Jake Mahoney [iteration number].' Each test was done independently of each other test, and each test was run forty times.

                    RESULTS:

                    Method #1 - printf("His name is : %s %s %d.",$fname, $lname, $i);

                    MIN: 2.4771 s
                    AVG: 2.7258 s
                    MAX: 3.9391 s

                    Methos #2 - print("His name is: " . $fname . " " . $lname . " " . $i . ".");

                    MIN: 2.5175 s
                    AVG: 2.7607 s
                    MAX: 3.5014 s

                    Method #3 - print('His name is: ' . $fname . ' ' . $lname . ' ' . $i . '.');

                    MIN: 2.4986 s
                    AVG: 2.7402 s
                    MAX: 3.4416 s

                    Method #4 - echo 'His name is: ' . $fname . ' ' . $lname . ' ' . $i . '.';

                    MIN: 2.4986 s
                    AVG: 2.7402 s
                    MAX: 3.4416 s

                    Method #5 - echo 'His name is: ' , $fname , ' ' , $lname, ' ', $i , '.';

                    MIN: 2.4650 s
                    AVG: 2.7446 s
                    MAX: 4.3656 s

                    Method #6 - echo "His name is: " . $fname . " " . $lname . " " . $i . ".";

                    MIN: 2.4838 s
                    AVG: 2.6925 s
                    MAX: 3.0803 s

                    Method #7 - echo "His name is: " , $fname, " ", $lname, " ", $i, ".";

                    MIN: 2.4875 s
                    AVG: 2.6858 s
                    MAX: 3.3571 s

                    Conclusions:

                    1 - I really need to get high. Soon!
                    2 - The Mets probably won't take the NL East pennant this year.
                    3 - Steve Howe is an incredible guitarist.

                      Well; all in all it pretty much confirms my opinion. There's no saving (at least for short, variable-dense strings) that would be measurable once things like buffering, bandwith constraints, TCP/IP protocol measures, and routing bottlenecks have been taken into account.

                      I think i'll try some longer paragraphs next. In fact, this could become a running topic for "which coding technique is faster, X or Y?" if we're not careful 🙂

                        Write a Reply...