Code: Select all

`$byteUnits = array(' B',' kB', ' MB', ' GB');`

$base = floor(log($size)/log(1024)); //find the power of 1024 in play

$size /= (1 << (10*$base)); //bitwise sorcery

//fails for file sizes greater than 2^90

$i = 0, $byteUnits = array(' B',' kB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB');

//find the largest unit that cannot be expressed as a whole number of the next largest

while($size > 1024){

$size /= 1024;

i++;

}

More fearsome things involving sprintf and regexes also abounded, all claiming efficiency, which I doubt, what with the reckless function calls. It made me curious, though, what is the most computationally efficient way of doing such a simple task? A case statement would just be a few branches and a single divide, which seems pretty cheap, but a loop has the elegance of an amusing little lookup table. I'm guessing grabbing characters out of an array [BkMGTPEZY] or some such would be more memory efficient, but I'm not sure if that'd be more or less efficient in its capacity as a lookup table.

What might say those who've had a proper algorithms class (neverminding that it's all roughly O(n))?