![](/img/trans.png)
[英]What is the absolute fastest way to read and write strings from a file with Java?
[英]Fastest way to read/write an array from/to a file?
我知道这里和网上都有几个类似的线程,但是我想我似乎做错了。 我的任务很简单-将一个大整数数组(int []或ArrayList或您认为最好的)写入(然后读取)。 越快越好。 我的具体数组中包含约4.5M整数,当前时间例如(以毫秒为单位):
这是不可接受的,我想时间应该少得多。 我究竟做错了什么? 我不需要地球上最快的方法,但我的目标是使这些时间达到5到15秒(欢迎的时间较短,但不是强制性的)。
我当前的代码:
long start = System.nanoTime();
Node trie = dawg.generateTrie("dict.txt");
long afterGeneratingTrie = System.nanoTime();
ArrayList<Integer> array = dawg.generateArray(trie);
long afterGeneratingArray = System.nanoTime();
try
{
new ObjectOutputStream(new FileOutputStream("test.txt")).writeObject(array);
}
catch (Exception e)
{
Logger.getLogger(DawgTester.class.getName()).log(Level.SEVERE, null, e);
}
long afterSavingArray = System.nanoTime();
ArrayList<Integer> read = new ArrayList<Integer>();
try
{
read = (ArrayList)new ObjectInputStream(new FileInputStream("test.txt")).readObject();
}
catch (Exception e)
{
Logger.getLogger(DawgTester.class.getName()).log(Level.SEVERE, null, e);
}
long afterLoadingArray = System.nanoTime();
System.out.println("Generating trie: " + 0.000001 * (afterGeneratingTrie - start));
System.out.println("Generating array: " + 0.000001 * (afterGeneratingArray - afterGeneratingTrie));
System.out.println("Saving array: " + 0.000001 * (afterSavingArray - afterGeneratingArray));
System.out.println("Loading array: " + 0.000001 * (afterLoadingArray - afterSavingArray));
不要使用Java序列化。 它非常强大,强大,但不是特别快(或紧凑)。 使用简单的DataOutputStream
并调用writeInt()
。 (确保在DataOutputStream
和FileOutputStream
之间使用BufferedOutputStream
)。
如果要在读取时对数组进行预大小调整,则将第一个int写入数组长度。
类似以下内容可能是一个相当快的选择。 如果您担心会减少开销,则还应该使用实际的数组int[]
而不是ArrayList<Integer>
。
final Path path = Paths.get("dict.txt");
...
final int[] rsl = dawg.generateArray(trie);
final ByteBuffer buf = ByteBuffer.allocateDirect(rsl.length << 2);
final IntBuffer buf_i = buf.asIntBuffer().put(rsl).flip();
try (final WritableByteChannel out = Files.newByteChannel(path,
StandardOpenOptions.WRITE, StandardOpenOptions.TRUNCATE_EXISTING)) {
do {
out.write(buf);
} while (buf.hasRemaining());
}
buf.clear();
try (final ReadableByteChannel in = Files.newByteChannel(path,
StandardOpenOptions.READ)) {
do {
in.read(buf);
} while (buf.hasRemaining());
}
buf_i.clear();
buf_i.get(rsl);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.