Java将布尔数组存储在文件中并快速读取

Mik*_*mov 1 java arrays io boolean

我需要在文件中存储包含 80,000 个项目的布尔数组。我不在乎节省多少时间,我只对数组的加载时间感兴趣。我没有尝试通过 DataOutputStream 存储它,因为它需要访问每个值。

我试图通过 3 种方法来做到这一点,例如:

  1. 序列化布尔数组
  2. 使用 BitSet 而不是布尔数组序列化它
  3. 将布尔数组转换为字节数组,其中 1 为真,0 为假,并通过 FileChannel 使用 ByteBuffer 写入

为了测试通过这些方法读取文件,我在循环中运行了每种方法 1,000 次。所以我得到了如下所示的结果:

  1. 布尔数组的反序列化需要 574 毫秒
  2. BitSet 的反序列化 - 379 毫秒
  3. 通过 MappedByteBuffer 从 FileChannel 获取字节数组 - 170 毫秒

第一种方法和第二种方法太长了,第三种方法可能根本就不是方法。

也许有最好的方法来完成它,所以我需要你的建议

编辑

每个方法运行一次

  1. 13.8
  2. 8.71
  3. 6.46 毫秒

dav*_*993 5

为每个布尔值编写一个字节并开发自定义解析器怎么样?这可能是最快的方法之一。如果您想节省空间,您也可以将 8 个布尔值放入一个字节中,但这需要一些位移操作。

这是一个简短的示例代码:

public void save() throws IOException
{
    boolean[] testData = new boolean[80000];
    for(int X=0;X < testData.length; X++)
    {
        testData[X] = Math.random() > 0.5;
    }
    FileOutputStream stream = new FileOutputStream(new File("test.bin"));

    for (boolean item : testData)
    {
        stream.write(item ? 1 : 0);
    }
    stream.close();
}

public boolean[] load() throws IOException
{
    long start = System.nanoTime();
    File file = new File("test.bin");
    FileInputStream inputStream = new FileInputStream(file);
    int fileLength = (int) file.length();

    byte[] data = new byte[fileLength];
    boolean[] output = new boolean[fileLength];

    inputStream.read(data);
    for (int X = 0; X < data.length; X++)
    {
        if (data[X] != 0)
        {
            output[X] = true;
            continue;
        }
        output[X] = false;
    }
    long end = System.nanoTime() - start;
    Console.log("Time: " + end);
    return output;
}
Run Code Online (Sandbox Code Playgroud)

加载 80.000 个布尔值大约需要 2 毫秒。使用 JDK 1.8.0_45 测试