Android问题:我想在文件而不是数据库中搜索字符串。因为我的数据需要加密。但是它非常非常慢,当我只是使用for或do-while来读取一个字节数组时,将它解析为一个类,使用类中的方法比较String。代码如下:
for (long p=0;positions[POS_WLIST]+p<positions[POS_BINDEX];) {
byte[] frame = this.getFrame(positions[POS_WLIST] + p); //getFrame(long position) is to read a long (length) and then read a byte[length] from a RandomAccessFile at position
Wort w = this.getWort(frame); //Wort is a message with protobuf, this method is a parseFrom(byte[]) method
String str=w.getW().toLowerCase();
if (str.length()>text.length()) {
if (str.contains(text)) {
//curOut.write(long2Byte(p));
n++;
}
}
p += frame.length + 3;
}
这个循环运行大约130000次,花费20秒,我得到了大量的GC_FOR_ALLOC(太多)。
dalvikvm GC_FOR_ALLOC freed 1373K, 27% free 18573K/25392K, paused 11ms, total 11ms
dalvikvm GC_FOR_ALLOC freed 1373K, 27% free 18573K/25392K, paused 22ms, total 22ms
....
如果发现问题不明显,请参阅:
FileInputStream fis=new FileInputStream(testFile);
byte[] lengthByte=new byte[4];
byte[] content=null;
int lengthInt=0;
for (int i=0;i<150000;i++) {
fis.read(lengthByte);
lengthInt=byte2Int(lengthByte);
content=new byte[lengthInt]; //10 bytes ~ 500 bytes at one time
fis.read(content);
//do something with content
}
即使没有与内容无关,也会在logcat中显示大量GC_FOR_ALLOC。
我如何实现这种简单的搜索算法?我不认为我可以避免写任何新的陈述。使用ObjectInputStream或BufferedReader,总时间仍然没有减少。有没有人面对这个GC_FOR_ALLOC问题?非常感谢你!