【问题标题】:Fastest and most efficient way to retrieve, sort, and manipulate data from a Extremely Large Text File [duplicate]从超大文本文件中检索、排序和操作数据的最快和最有效的方法 [重复]
【发布时间】:2020-03-02 17:20:23
【问题描述】:

我有一个文本文件,每一行都有文本,例如:


1245 哈士奇犬

2356 猫虎斑猫

3476 哈巴狗


每行重复大量任意数据,大约 10,000 行,为了论证,假设它趋于无穷。

我有代码可以读取这些数据并将其存储在一个对象中,下面是伪代码;

Pet P; 
lineInput = reader.readLine();  //where reader is reading the above mentionedfile
P.id = lineInput.split('\t')[0]     
P.type = lineInput.split('\t')[1]   //Assigning the parts of the line to it's relevant data members 
P.breed = lineInput.split('\t')[2]  

现在问题来了,考虑到我需要能够尽可能快地对这些值进行排序、搜索和显示,我不知道我最好的选择是什么,我想出了两种方法,如下所示

方法一:根据起始id号将所有对象存储在一个数组列表中

ArrayList<Pet> idStartsWith1;
if(P.id starts with 1)
     idStartsWith1.add(P);    // "1245    Dog    Husky" will be added here

ArrayList<Pet> idStartsWith2;
if(P.id starts with 2)
     idStartsWith2.add(P);   // "2356    Cat    Tabby" will be added here

ArrayList<Pet> idStartsWith3;
if(P.id starts with 3)
     idStartsWith3.add(P);   // "3476    Dog    Pug" will be added here

我认为这将是更快的方法,因为这些数组列表已经在进程内存中,但我担心它会超载内存并导致问题。 (记住,文本文件的行数趋于无限)

方法2:根据起始id号将所有对象写入.dat文件

Writer writer1 = new Writer("idStartsWith1.dat");    //writer1 will write to file "idStartsWith1.dat"
if(P.id starts with 1)
     writer1.write(P);    // "1245    Dog    Husky" will be writen to this file 

Writer writer2 = new Writer("idStartsWith2.dat");    //writer2 will write to file "idStartsWith2.dat"
if(P.id starts with 2)
     writer2.write(P);

Writer writer3 = new Writer("idStartsWith3.dat");    //writer3 will write to file "idStartsWith3.dat"
if(P.id starts with 3)
     writer3.write(P);

这将防止进程内存过载,但我担心每次需要搜索和显示 Pet 时都必须打开、读取、然后关闭文件,这会显着增加运行时延迟。

这两种方法中哪一种效果更好?还是像我这样的java新手不会想到另一种更有效的方法?

【问题讨论】:

  • 您说线条趋于无穷,但您说大约有 10.000 行……在大多数设备上,10K、100K、1M、10M 这样的线条,您也可以认为内存是无限的……行数有上限吗?
  • 你需要一个数据库。
  • @Matteo 我想上限大约是几百万

标签: java performance memory file-read


【解决方案1】:

许多应用程序的数据小到足以放入计算的桌面的主内存中。当您的文件有 1 GB 时,您需要大约 3 GB 的主内存,这对于大多数台式机来说都没有问题。在移动设备上,情况就不同了。

如果操作正确,没有什么能比使用主内存更快。 ArrayList 不能用于搜索,但 Map 可以。

您可以改用数据库,而且您可能应该这样做。它比将所有数据都放在主内存中要慢得多,但仍然非常快,假设你做得对(了解索引等)。大多数数据库可以直接导入 CSV 文件,并且能够回答您的所有查询 - 过滤、排序和连接其他表是数据库存在的目的。

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多