簡體   English   中英

將大文本文件加載到int數組中的最快方法

[英]Fastest way to load huge text file into a int array

我有一個大文本文件(+ 100MB),每行是一個整數(包含1000萬個數字)。 當然,尺寸和數量可能會有所變化,所以我事先並不知道。

我想將文件加載到int[] ,使進程盡可能快。 首先我來到這個解決方案:

public int[] fileToArray(String fileName) throws IOException
{
    List<String> list = Files.readAllLines(Paths.get(fileName));
    int[] res = new int[list.size()];
    int pos = 0;
    for (String line: list)
    {
        res[pos++] = Integer.parseInt(line);
    }
    return res;
}

它非常快,5.5秒。 其中,5.1s用於readAllLines調用,而0.4s用於循環。

但后來我決定嘗試使用BufferedReader,並找到了這個不同的解決方案:

public int[] fileToArray(String fileName) throws IOException
{
    BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(fileName)));
    ArrayList<Integer> ints = new ArrayList<Integer>();
    String line;
    while ((line = bufferedReader.readLine()) != null)
    {
        ints.add(Integer.parseInt(line));
    }
    bufferedReader.close();

    int[] res = new int[ints.size()];
    int pos = 0;
    for (Integer i: ints)
    {
        res[pos++] = i.intValue();
    }
    return res;
}

這更快! 3.1秒,只為3秒while循環並為連0.1秒for循環。

我知道這里沒有太多空間可供優化,至少在時間上,但是使用ArrayList然后使用int []對我來說似乎有太多的內存。

關於如何加快速度,或避免使用中間ArrayList的任何想法?

僅僅為了比較,我使用TStringList類和StrToInt函數在1.9秒內使用FreePascal執行相同的任務[請參閱編輯]。

編輯 :由於我用Java方法很短的時間,我不得不改進FreePascal。 330〜360ms。

如果您使用的是Java 8,則可以使用lines()然后映射到int ,然后將值收集到數組中來消除此中間ArrayList

您還應該使用try-with-resources進行正確的異常處理和自動關閉。

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
    return br.lines()
             .mapToInt(Integer::parseInt)
             .toArray();
}

我不確定這是否更快,但它肯定更容易維護。

編輯:它顯然要快得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM