Re: String construction

From: Date: Sun, 20 Aug 2000 23:27:46 +0000
Subject: Re: String construction
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-12691@lists.php.net to get a copy of this message
Jon Parise writes: > Is there any appreciable performance different between: > > a) $new_string = 'literal "' . $variable . '" literal'; > > ... and ... > > b) $new_string = sprintf('literal "%s" literal', $variable); > > I find the second method far more readable when looking at a complex > concatenation, but I'm curious whether it's much slower or more > resource intensive than the (perceivably) simpler dot concatenation. > > -- > Jon Parise (jon@csh.rit.edu) . Rochester Inst. of Technology > http://www.csh.rit.edu/~jon/ : Computer Science House Member Just did this for the hell of it: $loops = 400000; for ($i = 0; $i < $loops; $i++) { $str = sprintf('literal "%s" literal', $variable); } ...and ran it several times for each example. I also added one for comparison--call it option c): $str = "literal \"%s'\" literal"; Anyway, average results: a) 8.1 secs b) 15.7 secs c) 15.1 secs ...with no noticeable difference in server load or httpd memory footprint. However, changing the loop so that there is a contantly changing variable in the string has interesting results. For instance: a) $str = 'literal "' . $variable . '", "' . $i . '" literal'; b) $str = sprintf('literal "%s", "%d" literal', $variable, $i); c) $str = "literal \"$variable'\", \"$i\" literal"; ..results in: a) 15.8 secs b) 17.0 secs c) 28.8 secs In this case, sprintf() seems to start gaining on the competition, but a) is still slightly faster. Draw your own conclusions. :) There doesn't seem to be a whole lot to choose between them, unless you're working in tight loops or getting a zillion hits a minute. And even then, it depends on what's going into the string. Basically all this proves is that I've got *way* too much time on my hands on a Sunday afternoon. :) -- +----------------------------------------------------------------+ |Torben Wilson <torben@php.net> Netmill iTech| |http://www.coastnet.com/~torben http://www.netmill.fi| |Ph: 1 250 383-9735 torben@netmill.fi| +----------------------------------------------------------------+

« previous php.general (#12691) next »