有多少人被 Java 子字符串内存问题所困扰? [英] How many people have been stung by Java substring memory issues?

查看:35
本文介绍了有多少人被 Java 子字符串内存问题所困扰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现 java.lang.String.substring 方法不返回新字符串,而是返回子字符串化的原始字符串的视图.这可能会影响内存.例如,如果您正在读取一个 ascii 文件,并使用 substring 解析文件中的标记并将 substring 的结果存储在内存中的某处——您实际存储在内存中的是在 substring 操作之前的整个字符串!您当然可以通过将 substring 包装在您自己的版本中来解决这个问题,该版本返回 subtring 结果的新字符串.

I recently discovered that the java.lang.String.substring method does not return a new string, but a view of the original string that was substringed. This can have memory implications. For example, if you're reading an ascii file, and parsing tokens in the file using substring and storing the result of substring in memory somewhere -- what you're actually storing in memory is the entire string prior to the substring operation! You can of course solve this by wrapping substring in your own version that returns a new string of the subtring result.

推荐答案

我被它咬了一口,逐行阅读字典文件.每行都很短,但是 BufferedReader 创建的缓冲区意味着每个字符串都由一个 80 字符的数组支持.

I've been bitten by it once, reading a dictionary file line by line. Each line was very short, but the buffer created by BufferedReader meant that each string was backed by an 80-char array.

那是我第一次了解到写作的要点:

That was when I first learned the point of writing:

word = new String(word);

虽然大多数时候这不是问题 - 当然它比采取完全独立的副本"方法更有效.

Most of the time it's not a problem though - and of course it can be more efficient than the "take a completely separate copy" approach.

这篇关于有多少人被 Java 子字符串内存问题所困扰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆