Были ли некоторые тесты производительности для сравнения: от ip2long
до sprintf
против взрыва массива и затем временного или побитового сдвига:
<?php
header ('Content-Type: text/plain');
function ip_range($start, $count) {
$start = ip2long($start);
return array_map('long2ip', range($start, $start + $count) );
}
$iterations = 500000;
$results = array();
$ips = ip_range('192.168.1.1', $iterations);
$time = microtime(true);
foreach ($ips as $ip) {
$result = sprintf('%u', ip2long($ip));
}
$time = microtime(true) - $time;
$results['ip2long'] = array ('total' => $time, 'cycles' => $iterations, 'average' => ($time / $iterations) . 's', 'speed' => ($iterations/$time) . ' hashes per second.' );
$time = microtime(true);
foreach ($ips as $ip) {
$aIp = explode('.', $ip);
if (count($aIp) == 4) {
$result = /*sprintf('%u',*/ $aIp[0]*16777216 + $aIp[1]*65536 + $aIp[2]*256 + $aIp[3] /*)*/;
}
else
{
$result = false;
}
}
$time = microtime(true) - $time;
$results['explode multiple'] = array ('total' => $time, 'cycles' => $iterations, 'average' => ($time / $iterations) . 's', 'speed' => ($iterations/$time) . ' hashes per second.' );
$time = microtime(true);
foreach ($ips as $ip) {
$aIp = explode('.', $ip);
if (count($aIp) == 4) {
$result = /*sprintf('%u',*/ $aIp[3] | $aIp[2] << 8 | $aIp[1] << 16 | $aIp[0] << 24 /*)*/;
}
else
{
$result = false;
}
}
$time = microtime(true) - $time;
$results['explode bitwise'] = array ('total' => $time, 'cycles' => $iterations, 'average' => ($time / $iterations) . 's', 'speed' => ($iterations/$time) . ' hashes per second.' );
die(var_dump($results));
Вот результаты:
array(3) {
["ip2long"]=>
array(4) {
["total"]=>
float(0.92530012130737)
["cycles"]=>
int(500000)
["average"]=>
string(19) "1.8506002426147E-6s"
["speed"]=>
string(34) "540365.21609177 hashes per second."
}
["explode multiple"]=>
array(4) {
["total"]=>
float(0.91870212554932)
["cycles"]=>
int(500000)
["average"]=>
string(19) "1.8374042510986E-6s"
["speed"]=>
string(34) "544246.04678153 hashes per second."
}
["explode bitwise"]=>
array(4) {
["total"]=>
float(0.9184091091156)
["cycles"]=>
int(500000)
["average"]=>
string(19) "1.8368182182312E-6s"
["speed"]=>
string(34) "544419.68730197 hashes per second."
}
}
При обтекании поразрядным и умножением на sprintf
они медленнее, чем ip2long
, но поскольку это не нужно, они быстрее.