Benchmarked the following five functions:
// For a baseline, returns unpadded binary
function decBinPlain(int $x) {
return decbin($x);
}
// Alas fancier than necessary:
function decBinDig(int $x) {
return substr(decbin(pow(2, 8) + $x), 1);
}
// OP's initial test
function getBinary(int $x) {
return str_pad(base_convert($x, 10, 2), 8, '0', STR_PAD_LEFT);
}
// OP's function using decbin()
function getDecBin(int $x) {
return str_pad(decbin($x), 8, '0', STR_PAD_LEFT);
}
// TimBrownlaw's method
function intToBin(int $x) {
return sprintf( "%08d", decbin($x));
}
At 500,000 iterations each, run as 10 x (50,000 @ 5), here are the stats:
[average] => [
[decBinPlain] => 0.0912
[getDecBin] => 0.1355
[getBinary] => 0.1444
[intToBin] => 0.1493
[decBinDig] => 0.1687
]
[relative] => [
[decBinPlain] => 100
[getDecBin] => 148.57
[getBinary] => 158.33
[intToBin] => 163.71
[decBinDig] => 184.98
]
[ops_per_sec] => [
[decBinPlain] => 548355
[getDecBin] => 369077
[getBinary] => 346330
[intToBin] => 334963
[decBinDig] => 296443
]
The positions are consistent. OP's function, changed to use decbin in place of base_convert, is the fastest function that returns the complete result, by a very thin margin. I'd opt for decbin simply because the meaning is crystal clear. For adding in the left-padding, str_pad is less complex than sprintf. Running PHP 7.4.4 on W10 & i5-8250U, total runtime 7.11 sec.
For a baseline, calling an empty dummy function averages 0.0542 sec. Then: If you need to run this enough times to worry about minute per-op performance gains, it's more economical to have the code inline to avoid the function call. Here, the overhead from the function call is greater than the difference between the slowest and the fastest options above!
For future reference. If you're bench-marking several options, I'd recommend testing them over a single script call and over several consecutive loops of each function. That'll help even out any "lag noise" from background programs, CPU throttling (power to max if on battery!!) etc. Then, call it a couple of times and see that the numbers are stable. You'll want to do much more than 1000 iterations to get reliable numbers. Try e.g. 10K upwards for more complex functions, and 100K upwards for simpler functions. Burn it enough if you want to prove it!
$st=""; while($n>0){ $st = ($n%2) . $st; $n=intval($n/2); } echo $st;. I don't know how you're measuring the time. Can you try this and let me know here. Thanks in advance :)$startTime = microtime(true); getBinary(89); $endTime = microtime(true); $elapsed = round(($endTime - $startTime) * 1000000, 2); echo "Execution time : $elapsed ms";getBinary()and does not produce the desired eight characters