F
F
floppa3222021-03-24 17:55:31
Java
floppa322, 2021-03-24 17:55:31

Why is the speed of bit operations different by a factor of 1000?

In this cycle, for each of the elements of the original array, each bit of the byte of this array is written into the variable bit in 2 different ways, the difference in speed is about 1000 times. My guess is that the MASKs array is evicted from the CPU cache (which is unlikely), while the MASK variable is not. Does anyone else have any guesses as to what's wrong?

final byte[] MASKS =
        {
            (byte) 0b1000_0000, // 0
            (byte) 0b0100_0000, // 1
            (byte) 0b0010_0000, // 2
            (byte) 0b0001_0000, // 3
            (byte) 0b0000_1000, // 4
            (byte) 0b0000_0100, // 5
            (byte) 0b0000_0010, // 6
            (byte) 0b0000_0001, // 7
        };
final  byte MASK = (byte) 0b1000_0000;
int BYTE_COUNT = 2_000_000_000;

byte[] bytes = new byte[BYTE_COUNT];
byte bit;

double start = System.nanoTime();

for (int i = 0; i < BYTE_COUNT; ++i)
{
        byte currentByte = bytes[i];
         for (int j = 0; j < 8; ++j)
            {
                bit = (byte) (currentByte & MASKS[j]); // Elapsed time 6.2994273

//                bit = (byte) ((currentByte << j) & MASK); // Elapsed time 0.0054073
            }
}

double elapsedTime = (System.nanoTime() - start) / 1e9;
System.out.println("Elapsed time " + elapsedTime);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-03-24
@Lite_stream

Most likely, accessing the array slows down. There, apparently, there are also checks for hitting the array boundaries.
If you do an array call currentByte & (1 << (7-j)), it should work almost as fast.
Ps and in general you have some strange choice of bit order. Usually shifted to the right, to the least significant bit. Then instead of a mask it will be stupidly 0x1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question