I would use a long [] instead of a logical []. Each long one has 64 bits, and you can perform combined operations such as
if (the_array[iter] == -1L) // all 1s the_array[iter] = 0L; // all zeros.
You can perform 64-bit operations at about the same time as the logical operation, making the loop up to 64x faster.
BTW: using boolean[]
will use 8 times more memory than long[]
, since each boolean
uses memory bytes in most JVMs.
Examples of using longer types for storing data.
Depending on what operations you perform, using int
may be easier to work with, for example. x = (long) a * b
will overflow with long
, but not int
.
If you scan multiple bits (as BitSet can do), then using long[]
can be faster.
Adding a benchmark showing the difference in time that it can make.
public static final int RUNS = 100; public static void main(String... args) throws InterruptedException { boolean[] bools = new boolean[1024 * 1024]; long[] longs = new long[bools.length / 64]; for (int i = 0; i < 5; i++) { testBools(bools); testLongs(longs); } } private static void testBools(boolean[] bools) { long start = System.nanoTime(); for (int t = 0; t < RUNS; t++) { // set all to true for (int i = 0; i < bools.length; i++) bools[i] = true; // search for a false; for (boolean b : bools) if (!b) throw new AssertionError(); // set all to false for (int i = 0; i < bools.length; i++) bools[i] = false; // search for a true; for (boolean b : bools) if (b) throw new AssertionError(); } long time = System.nanoTime() - start; System.out.printf("To set and scan a boolean[] with %,d bits took %,d us%n", bools.length, time / 2/ RUNS / 1000); } private static void testLongs(long[] longs) { long start = System.nanoTime(); for (int t = 0; t < RUNS; t++) { // set all to true for (int i = 0; i < longs.length; i++) longs[i] = ~0; // all 1s // search for a false; for (long l : longs) if (l != ~0) throw new AssertionError(); // set all to false for (int i = 0; i < longs.length; i++) longs[i] = 0; // all 0s // search for a true; for (long l : longs) if (l != 0) throw new AssertionError(); } long time = System.nanoTime() - start; System.out.printf("To set and scan a long[] with %,d bits took %,d us%n", longs.length * Long.SIZE, time / 2/ RUNS / 1000); }
prints
To set and scan a boolean[] with 1,048,576 bits took 777 us To set and scan a long[] with 1,048,576 bits took 104 us To set and scan a boolean[] with 1,048,576 bits took 666 us To set and scan a long[] with 1,048,576 bits took 20 us To set and scan a boolean[] with 1,048,576 bits took 537 us To set and scan a long[] with 1,048,576 bits took 18 us To set and scan a boolean[] with 1,048,576 bits took 567 us To set and scan a long[] with 1,048,576 bits took 28 us To set and scan a boolean[] with 1,048,576 bits took 776 us To set and scan a long[] with 1,048,576 bits took 27 us
In this example, it is about 30 times slower to use a boolean[]
compared to a long[]