Java store boolean array in file and read fast -
i need store boolean array 80,000 items in file. don't care how time saving takes, i'm interested in loading time of array. did't try store dataoutputstream because requires access each value.
i tried make 3 approaches, such as:
- serialize boolean array
- use bitset instead of boolean array serialize it
- transfer boolean array byte array, 1 true , 0 false appropriately , write filechannel using bytebuffer
to test reading files these approaches, had run each approach 1,000 times in loop. got results this:
- deserialization of boolean array takes 574 ms
- deserialization of bitset - 379 ms
- getting byte array filechannel mappedbytebuffer - 170 ms
the first , second approaches long, third, perhaps, not approach @ all.
perhaps there best way accomplish it, need advice
edit
each method ran once
- 13.8
- 8.71
- 6.46 ms appropriatively
what writing byte each boolean , develop custom parser? propably 1 of fastest methods. if want save space put 8 booleans 1 byte require bit shifting operations.
here short example code:
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")); (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); (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; }
it takes 2ms load 80.000 booleans. tested jdk 1.8.0_45
Comments
Post a Comment