Sprintf or direct assignment



  • Assuming internationalization (gettext translation) is not needed.  Is it better to use sprintf or direct assignment to build up str?  Especially if there are many to do.  Say few a dozen.

    Are there any lurking gotchas that would make one or the other less desirable?
    I know it would not be user perceptible, but which one takes less processing to accomplish?

    Just thinking why make a bunch of sprintf calls if no benefit.

    
    $str .= sprintf ("Some text %s\n", $var);
    $str .= "Some text ". $var . "\n";
    
    


  • Lots of discussion on this sort of thing, like at:
    http://stackoverflow.com/questions/17012284/concatenation-multiple-parameters-or-sprintf
    and
    https://r.je/sprintf.html
    which down the bottom does say that sprintf() for language translation is "a good thing".

    String concat of some sort will be faster than sprintf() just because of the obvious function call overhead.

    In pfSense most of the strings that have literal text mixed with vars need to be translated anyway. But sure, if there is not need for translation then just concat the pieces together.


  • Rebel Alliance Developer Netgate

    You missed an option:

    $str .= "Some text {$var}\n";
    

    If translation isn't a factor, I'd only use sprintf if I wanted its formatting features, such as presenting numbers with a fixed number of decimal places or leading zeros.



  • Kind of torn between the alternatives.

    Found this quote interesting.  Never thought of the opcache.
    http://stackoverflow.com/questions/7147305/performance-of-variable-expansion-vs-sprintf-in-php

    Ultimately the 1st is the fastest when considering the context of a single variable assignment which can be seen by looking at various benchmarks. Perhaps though, using the sprintf flavor of core PHP functions could allow for more extensible code and be better optimized for bytecode level caching mechanisms like opcache or apc. In other words, a particular sized application could use less code when utilizing the sprintf method. The less code you have to cache into RAM, the more RAM you have for other things or more scripts. However, this only matters if your scripts wouldn't properly fit into RAM using evaluation.

    Sounds like single quote (nowdocs) catenation may be fastest when only a single var.  But then there is that opcache thing and memory mentioned in the quote.


Log in to reply