【发布时间】: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