Java:有效存储布尔值[32]?

nav*_*ige 10 java performance

在Java中,我想将长度为32的布尔值(boolean [])数组(> 10'000)存储到磁盘中,稍后再次读取它们以进行进一步的计算和比较.

由于单个数组的长度为32,我想知道将它存储为整数值以加快读写速度是有意义的(在32位机器上).你会建议使用BitSet然后转换为int吗?甚至忘记int和使用字节?

Ste*_*ein 11

对于二进制存储,使用int和a DataOutputStream(DataInputStream用于读取).

我认为布尔数组在Java内部存储为byte或int数组,因此您可能需要考虑避免开销并始终保持int编码,即根本不使用boolean [].

相反,有类似的东西

public class BooleanArray32 {
  private int values;

  public boolean get(int pos) {
    return (values & (1 << pos)) != 0;
  }

  public void set(int pos, boolean value) {
     int mask = 1 << pos;
     values = (values & ~mask) | (value ? mask : 0);
  }

  public void write(DataOutputStream dos) throws IOException {
    dos.writeInt(values);
  }

  public void read(DataInputStream dis) throws IOException {
    values = dis.readInt();
  }

  public int compare(BooleanArray32 b2) {
     return countBits(b2.values & values);
  }

  // From http://graphics.stanford.edu/~seander/bithacks.html
  // Disclaimer: I did not fully double check whether this works for Java's signed ints
  public static int countBits(int v) {
    v = v - ((v >>> 1) & 0x55555555);                    // reuse input as temporary
    v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);     // temp
    return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; 
  }
} 
Run Code Online (Sandbox Code Playgroud)