Darren,
Thanks very much for your response. Your code does exactly what I was
looking for--excellent. I haven't tested it with all input, but at a
first cut, it's creating the arrays correctly.
will be called in a loop, 1000 times or so.
I've 'function-ised' Darren's code below, it runs 10,000 'getBytes()' in
about 200ms (Firefox) or 220ms (IE) on a 2.4GH P4.
One idea I had is to not create the array in memory each time, but
actually pass it in as a parameter and reuse it. That should save 1000
dynamic array allocations (I'll do some metrics later).
You've gotta create the array sometime, and it takes very little time.
If I know the integer is going to be bounded between 1 and 1000, one or
more of the chunks doesn't need to be calculated... I think only two
would need to be (255 * 255). So that should speed things up by two.
For very large sets of numbers that are all within a range it maybe
worth it but the time spent calculating how many loops to do may take
longer than doing the loops.
There is an optimised version below called getBytes0 that stops looping
when x =0, it trims about 10% from the time but the array will have
undefined values for the missed loops - dealing with that may take back
the 10%.
Also, what is the best format to perform bit operations with (the "&"
operator)? 255, or is a hex representation (0xFF or similar) better? In
this line, var a = x & (255), is the 255 being caster to a different
data type?
Testing 255 vs 0xFF made no measurable difference, if there may be other
more meaningful optimisations.
<div id="msg2" style="font-weight:bold;"></div>
<p>Click reload to run again...</p>
<p>Enter a number and click elsewhere in the document</p>
<input type="text" onblur="
document.getElementById('msg').innerHTML =
getBytes(this.value).join('<br>');">
<p></p>
<div id="msg"></div>
<script type="text/javascript">
// Does exactly 4 loops
function getBytes( x ){
var bytes = [];
var i = 4;
do {
bytes[--i] = x & (255);
x = x>>8;
} while ( i )
return bytes;
}
// Stops looping when x = 0
function getBytes0( x ){
var bytes = [];
var i = 4;
do {
bytes[--i] = x&(255);
x = x>>8;
} while ( i && x > 0 )
return bytes;
}
/* Generate an array of numValues random integers
between 0 and 100,000, then do getBytes on them
and time it
*/
var j, sTime, fTime;
var numValues = 10000;
var randArray = [];
for ( j=0; j<numValues; j++) {
randArray[j] = (Math.random()*100000) | 0;
}
j = numValues;
sTime = new Date();
while ( j-- ) {
getBytes( randArray[j] )
}
fTime = new Date();
document.getElementById('msg2').innerHTML =
( 'Doing ' + numValues + ' values took ' + (fTime - sTime) + 'ms');
</script>