← Back to context

Comment by mananaysiempre

1 year ago

This is perfectly usable, of course, but I’d write

  var actualSize = Integer.highestOneBit(approxSize - 1) << 1;

purely to avoid involving the horrors that live beneath the humble pow() and log().

(Integer.highestOneBit, also known as “isolate leftmost bit”, “most significant one”, or the like, essentially has to be a primitive to be efficient, unlike its counterpart for the lowest bit, x&-x. The actual CPU instruction is usually closer to Integer.numberOfLeadingZeros, but that’s just a bitshift away.)

The above gives an incorrect result for approxSize = 1 (namely 0). The following works (for values up to 2^30, of course):

    var actualSize = Integer.MIN_VALUE >>> Integer.numberOfLeadingZeros(approxSize - 1) - 1;

Or, if you want 0 to map to 0 instead of to 1:

    var actualSize = Integer.signum(approxSize) * Integer.MIN_VALUE >>> Integer.numberOfLeadingZeros(approxSize - 1) - 1;

Of course, you could also use a variation of:

    var actualSize = Math.min(1, Math.Integer.highestOneBit(approxSize - 1) << 1);

That's pretty cool; I didn't even consider doing any cool bitwise arithmetic.

I didn't particularly care about performance or anything for this particular case, since it runs exactly once at the start of the app just to initiate the Disruptor.

shouldn't it be

var actualSize = 1 << Integer.highestOneBit(approxSize - 1);

?