简体   繁体   English

是否建议将大字符串存储在内存中或重复读取文件?

[英]Is it advisable to store large strings in memory, or repeatedly read a file?

Let's say I have various text/json/xml/whatever files (stored locally, in the assets directory), ranging in size from 20 - 500 KB. 假设我有各种text / json / xml /任何文件(存储在本地,在assets目录中),大小从20-500 KB不等。 Assuming these files are going to be referenced frequently, throughout the application, is it better to: 假设在整个应用程序中经常要引用这些文件,那么最好这样做:

A) Read the file once, the first time it's requested, and store the data in a variable A)第一次读取文件时,将其存储在变量中

or 要么

B) Read the file each time it's requested, grab the requested bit of information, and allow GC to clean up afterward? B)每次请求时都读取文件,获取请求的信息,然后让GC清理吗?

Coming from web-dev, I generally use option (A), but I wonder if the storage limitation of mobile devices makes B preferred in this context (Android app development). 来自web-dev,我通常使用选项(A),但我想知道在这种情况下(Android应用程序开发)移动设备的存储限制是否使B成为首选。

TYIA. TYIA。

You can store your data into memory by compressing it.That it will reduce your memory footprint at any point of time.So this technique can be applicable to both PCs and mobile phones.Later on when you need the data, read and decompress it.So read the file once, then compress and store it in the memory.The following example uses GZIPOutputStream to compress a string. 您可以通过压缩将数据存储到内存中,这样可以在任何时间减少内存占用量,因此该技术可适用于PC和移动电话,稍后在需要数据时对其进行读取和解压缩。因此,一次读取文件,然后将其压缩并存储在内存中。以下示例使用GZIPOutputStream压缩字符串。

public static String compress(String str){
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(str.getBytes());
    gzip.close();
    return out.toString("ISO-8859-1");
 }

If the file is being requested frequently, definitely it's better to read the file once and store in cache. 如果经常请求文件,则绝对最好一次读取文件并存储在缓存中。

You can also read this article titled How Google Taught me to Cache and Cash In in HighScalability website. 您还可以在HighScalability网站上阅读标题为Google如何教我如何进行缓存和取现的文章。

That depends on the total size of the files, accessing frequency, and your targeting customers. 这取决于文件的总大小,访问频率以及您的目标客户。 Although high-end phone got very large memory, the are many low-ends system which has fewer memory. 尽管高端电话具有非常大的内存,但许多具有较少内存的低端系统。 It might deserve to use some LRU cache to reach a balance. 可能应该使用一些LRU缓存来达到平衡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM