【问题标题】:Fast Serialization - Android快速序列化 - Android
【发布时间】:2014-08-29 16:07:44
【问题描述】:

我的任务是在 Android 手机上处理大量文本数据。 (出于隐私原因,需要在手机上进行处理)我有一个关键字对象,我必须将它与字符串消息进行比较,这个对象包含两个 ArrayList、两个 int id 和一个布尔值,问题是我们有 50000 + 这些对象。在内存中保留这些对象的列表会导致内存不足 1.5 GB 的手机出现 OutOfMemory 异常。我们当前的实现是将列表序列化为文件,然后根据需要一次反序列化每个对象。通过这种实现,我们保持了低内存配置文件,并将其优化为每条消息的 5 秒处理时间。他们希望它具有低内存,但理想情况下每秒处理 3 或 4 个。我并不是说这是一个可行的要求。我只是想问问 StackOverFlow 的专家,看看是否有人对我们如何加快这个过程有任何想法。

对于序列化,我已经实现了外部化。这是代码。

@Override
public void readExternal(ObjectInput input) throws IOException, ClassNotFoundException
{
    groupID = input.readInt();
    keywordID = input.readInt();
    mapped = input.read() == 1;
    int length = input.readInt();
    int piecelength;
    for(int index = 0; index < length; index++)
    {
        piecelength = input.readInt();
        byte[] piece = new byte[piecelength];
        input.read(piece);
        keywordPieces.add(new String(piece));           
    }
    length = input.readInt();
    for(int index = 0; index < length; index++)
    {
        piecelength = input.readInt();
        byte[] piece = new byte[piecelength];
        input.read(piece);
        positiveKeywordPieceFragments.add(new String(piece));           
    }
}

@Override
public void writeExternal(ObjectOutput output) throws IOException
{
    output.writeInt(groupID);
    output.writeInt(keywordID);
    output.write(mapped ? 1 : 0);
    output.writeInt(keywordPieces.size());
    for(int index = 0; index < keywordPieces.size(); index++)
    {
        byte[] piece = keywordPieces.get(index).getBytes();
        output.writeInt(piece.length);  
        output.write(piece);            
    }
    output.writeInt(positiveKeywordPieceFragments.size());
    for(String s : positiveKeywordPieceFragments)
    {
        byte[] piece = s.getBytes();
        output.writeInt(piece.length);  
        output.write(piece);            
    }
}

这是文件读取代码

input = new ObjectInputStream( new BufferedInputStream(new FileInputStream(keywordsFile)));
int length = input.readInt();
Keyword keyword;
for(int index = 0; index < length; index++)
{
    keyword = (Keyword) input.readObject();
    callback.onKeywordRead(keyword);
    keyword = null;
}

任何你能想到的能加快速度的东西都很棒。

编辑:

当前实现之前的循环如下所示

for(Keyword keyword : keywords)

关键字只是保存在内存中,但是,就像我上面所说的,当填充列表时,这会在旧设备上导致 OutOfMemoryException。它存储在一个 ArrayList 中

【问题讨论】:

    标签: android performance memory serialization


    【解决方案1】:

    如果我理解正确,您有 50K 条记录,其中大部分无法加载到 RAM 中,并且数据架构有利于数据读取而不是数据写入。


    如果是这种情况,请使用数据库。索引您要用于快速检索数据的字段(最好是

      db.execSQL( "Create Index MyTable_StartDate_idx ON MyTable(StartDate);"
    


    .. 在合理的时间内,您将获得远远超过您自己可以做的任何事情的性能。


    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      相关资源
      最近更新 更多