我有一个很大的文本文件(+ 100MB),每行都是一个整数(包含1000万个数字)。当然,规模和金额可能会改变,所以我不知道这事。将大文本文件加载到int数组中的最快方法
我想将文件加载到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秒,while
循环仅为3秒,而for
循环仅为0.1秒。
我知道这里没有太多空间用于优化,至少在时间上,但使用ArrayList然后int []似乎对我来说太多的内存。
任何想法如何使这更快,或避免使用中间的ArrayList?
只是为了比较,我在1.9秒内用FreePascal完成了这个任务[见编辑],使用TStringList
类和StrToInt
函数。
编辑:由于我用Java方法得到了很短的时间,我不得不改进FreePascal。 330〜360ms。
看起来你已经收集了一些很好的指标。你可能想看看在https://stackoverflow.com/questions/13155700/fastest-way-to-read-and-write-large-files-line-by-line-in-java – Jameson
你可以试试这个ArrayList ints = new ArrayList (); Integer [] res = ints.toArray(new Integer [ints.size()]); –
ravthiru
您可以通过获取文件大小来近似文件中的整数数量吗?你可以把它传递给你的ArrayList <>作为构造函数的初始容量,也许它不需要增长很多次。 –