Http build query

Today during code review Olle noticed that there is much simpler way to build query part of url then concatenate strings in loop.

For example instead of:

$aParams = array('id' => 12,
	'method' => 'post',
	'callback_function_name' => 'add');
$sQuery = '?';
foreach ($aParams as $key => $value) {
	$sQuery .= $key .'=' .$value .'&';
}
$sQuery = substr($sQuery, 0, -1); //to remove last &
$sUrl = $sHost .$sQuery;

Solution proposed by Olle was:

$aParams = array('id' => 12,
	'method' => 'post',
	'callback_function_name' => 'add');
$sQuery = http_build_query($aParams, '', '&');
$sUrl = $sHost . $sQuery;

I checked that function in manual and it looks quite powerful. One thing which considered me was performance, of course native C function are faster then loop, etc, but is not that function too powerful and slow to use it in responsible part of code with huge load?

Lets check:

$aParams = array('id' => 12,
	'user_id' => 234,
	'method' => 'post',
	'callback_function_name' => 'add');

$fStarttime = microtime(true);

for ($i = 0; $i < 100000; $i++) {
	$sQuery = http_build_query($aParams, '', '&');
}
echo 'http_build_query: ' . (microtime(true) - $fStarttime) .PHP_EOL;

$fStarttime = microtime(true);

for ($i = 0; $i < 100000; $i++) {
	$sQuery = '';
	foreach ($aParams as $key => $value) {
		$sQuery .= $key . '=' . $value . '&';
	}
	$sQuery = substr($sQuery, 0, -1); //to remove last &
}
echo 'concatenation: ' . (microtime(true) - $fStarttime);

and results:

http_build_query: 0.69601511955261
concatenation:    1.1222679615021

As you see it is definitely easier, faster way and needs less lines of code.

Tip: there is an extension called http://dk.php.net/manual/en/book.http.php which posses more useful function.

In PHP5.4 second approach will faster due to introduce caches to eliminate repeatable run-time bindings of functions, classes, constants, methods and properties – more info about this feature here

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">