java慎用String.substring(int start, int end)

2024-06-07 20:38

本文主要是介绍java慎用String.substring(int start, int end),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1:问题的抛出

        今天在安卓项目中使用后台线程操作一个大文件,分块读取文件中的所有内容,每次操作加载一个小块进行解析,解析到指定的文本内容之后会加载并常驻内存中,即使所有我解析到的文本内容被加入到内存中也不会很大,这样不会造成内存泄露问题。原理如此,但是最终依然出现oom。

2:问题的排查

仔细检查之后发现线程中所有的产生的对象都已经在操作结束之后回收(即:生成的对象没有引用)。代码很简短,挨个排查,发现一个string对象调用了substring(int start, int end)方法,查看了一下substring方法的注释:

Returns a string containing a subsequence of characters from this string. The returned string shares this string's backing array.

注释中的这句话"shares this string's backing array"让我产生一个疑问:什么是backing array,会不会是原来string的所有内容数组?带着这个问题,我把调用该方法的代码注释掉再次运行,哈哈,果然顺畅了。

3:产生的原因

定位到String.substring(int start, int end)的源代码:

public String substring(int start, int end) {if (start == 0 && end == count) {return this;}// NOTE last character not copied!// Fast range check.if (start >= 0 && start <= end && end <= count) {return new String(offset + start, end - start, value);}throw startEndAndLength(start, end);}

可见,正常情况下返回的是new String(offset + start, end - start, value);这个新的字符串,重点看看那个value参数到底是什么呢,源码中定义为:

private final char[] value;

我在构造自己的String的时候使用的是 String (byte[] data)构造方法,追溯到value数组初始化的地方:

 public String(byte[] data, int offset, int byteCount, Charset charset) {if ((offset | byteCount) < 0 || byteCount > data.length - offset) {throw failedBoundsCheck(data.length, offset, byteCount);}// We inline UTF-8, ISO-8859-1, and US-ASCII decoders for speed and because 'count' and// 'value' are final.String canonicalCharsetName = charset.name();if (canonicalCharsetName.equals("UTF-8")) {byte[] d = data;char[] v = new char[byteCount];int idx = offset;int last = offset + byteCount;int s = 0;
outer:while (idx < last) {byte b0 = d[idx++];if ((b0 & 0x80) == 0) {// 0xxxxxxx// Range:  U-00000000 - U-0000007Fint val = b0 & 0xff;v[s++] = (char) val;} else if (((b0 & 0xe0) == 0xc0) || ((b0 & 0xf0) == 0xe0) ||((b0 & 0xf8) == 0xf0) || ((b0 & 0xfc) == 0xf8) || ((b0 & 0xfe) == 0xfc)) {int utfCount = 1;if ((b0 & 0xf0) == 0xe0) utfCount = 2;else if ((b0 & 0xf8) == 0xf0) utfCount = 3;else if ((b0 & 0xfc) == 0xf8) utfCount = 4;else if ((b0 & 0xfe) == 0xfc) utfCount = 5;// 110xxxxx (10xxxxxx)+// Range:  U-00000080 - U-000007FF (count == 1)// Range:  U-00000800 - U-0000FFFF (count == 2)// Range:  U-00010000 - U-001FFFFF (count == 3)// Range:  U-00200000 - U-03FFFFFF (count == 4)// Range:  U-04000000 - U-7FFFFFFF (count == 5)if (idx + utfCount > last) {v[s++] = REPLACEMENT_CHAR;continue;}// Extract usable bits from b0int val = b0 & (0x1f >> (utfCount - 1));for (int i = 0; i < utfCount; ++i) {byte b = d[idx++];if ((b & 0xc0) != 0x80) {v[s++] = REPLACEMENT_CHAR;idx--; // Put the input char backcontinue outer;}// Push new bits in from the right sideval <<= 6;val |= b & 0x3f;}// Note: Java allows overlong char// specifications To disallow, check that val// is greater than or equal to the minimum// value for each count://// count    min value// -----   ----------//   1           0x80//   2          0x800//   3        0x10000//   4       0x200000//   5      0x4000000// Allow surrogate values (0xD800 - 0xDFFF) to// be specified using 3-byte UTF values onlyif ((utfCount != 2) && (val >= 0xD800) && (val <= 0xDFFF)) {v[s++] = REPLACEMENT_CHAR;continue;}// Reject chars greater than the Unicode maximum of U+10FFFF.if (val > 0x10FFFF) {v[s++] = REPLACEMENT_CHAR;continue;}// Encode chars from U+10000 up as surrogate pairsif (val < 0x10000) {v[s++] = (char) val;} else {int x = val & 0xffff;int u = (val >> 16) & 0x1f;int w = (u - 1) & 0xffff;int hi = 0xd800 | (w << 6) | (x >> 10);int lo = 0xdc00 | (x & 0x3ff);v[s++] = (char) hi;v[s++] = (char) lo;}} else {// Illegal values 0x8*, 0x9*, 0xa*, 0xb*, 0xfd-0xffv[s++] = REPLACEMENT_CHAR;}}if (s == byteCount) {// We guessed right, so we can use our temporary array as-is.this.offset = 0;this.value = v;this.count = s;} else {// Our temporary array was too big, so reallocate and copy.this.offset = 0;this.value = new char[s];this.count = s;System.arraycopy(v, 0, value, 0, s);}} else if (canonicalCharsetName.equals("ISO-8859-1")) {this.offset = 0;this.value = new char[byteCount];this.count = byteCount;Charsets.isoLatin1BytesToChars(data, offset, byteCount, value);} else if (canonicalCharsetName.equals("US-ASCII")) {this.offset = 0;this.value = new char[byteCount];this.count = byteCount;Charsets.asciiBytesToChars(data, offset, byteCount, value);} else {CharBuffer cb = charset.decode(ByteBuffer.wrap(data, offset, byteCount));this.offset = 0;this.count = cb.length();if (count > 0) {// We could use cb.array() directly, but that would mean we'd have to trust// the CharsetDecoder doesn't hang on to the CharBuffer and mutate it later,// which would break String's immutability guarantee. It would also tend to// mean that we'd be wasting memory because CharsetDecoder doesn't trim the// array. So we copy.this.value = new char[count];System.arraycopy(cb.array(), 0, value, 0, count);} else {this.value = EmptyArray.CHAR;}}}

看看源码就终于明白了,value长度就是原有byte数组根据不同编码计算得到的结果,其内容自然是字符串中所有数据内容。

4:总结

java中的String.substring(int start, int end)方法返回的新字符串仍然保持原来字符串的数据引用,如果数据量比较大,这里需要注意一下会不会产生内存问题。

这篇关于java慎用String.substring(int start, int end)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1040243

相关文章

redis在spring boot中异常退出的问题解决方案

《redis在springboot中异常退出的问题解决方案》:本文主要介绍redis在springboot中异常退出的问题解决方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴... 目录问题:解决 问题根源️ 解决方案1. 异步处理 + 提前ACK(关键步骤)2. 调整Redis消费者组

一文教你Java如何快速构建项目骨架

《一文教你Java如何快速构建项目骨架》在Java项目开发过程中,构建项目骨架是一项繁琐但又基础重要的工作,Java领域有许多代码生成工具可以帮助我们快速完成这一任务,下面就跟随小编一起来了解下... 目录一、代码生成工具概述常用 Java 代码生成工具简介代码生成工具的优势二、使用 MyBATis Gen

springboot项目redis缓存异常实战案例详解(提供解决方案)

《springboot项目redis缓存异常实战案例详解(提供解决方案)》redis基本上是高并发场景上会用到的一个高性能的key-value数据库,属于nosql类型,一般用作于缓存,一般是结合数据... 目录缓存异常实践案例缓存穿透问题缓存击穿问题(其中也解决了穿透问题)完整代码缓存异常实践案例Red

SpringCloud整合MQ实现消息总线服务方式

《SpringCloud整合MQ实现消息总线服务方式》:本文主要介绍SpringCloud整合MQ实现消息总线服务方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、背景介绍二、方案实践三、升级版总结一、背景介绍每当修改配置文件内容,如果需要客户端也同步更新,

java中XML的使用全过程

《java中XML的使用全过程》:本文主要介绍java中XML的使用全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录什么是XML特点XML作用XML的编写语法基本语法特殊字符编写约束XML的书写格式DTD文档schema文档解析XML的方法​​DOM解析XM

Java 的 Condition 接口与等待通知机制详解

《Java的Condition接口与等待通知机制详解》在Java并发编程里,实现线程间的协作与同步是极为关键的任务,本文将深入探究Condition接口及其背后的等待通知机制,感兴趣的朋友一起看... 目录一、引言二、Condition 接口概述2.1 基本概念2.2 与 Object 类等待通知方法的区别

SpringBoot项目中Redis存储Session对象序列化处理

《SpringBoot项目中Redis存储Session对象序列化处理》在SpringBoot项目中使用Redis存储Session时,对象的序列化和反序列化是关键步骤,下面我们就来讲讲如何在Spri... 目录一、为什么需要序列化处理二、Spring Boot 集成 Redis 存储 Session2.1

使用Java实现Navicat密码的加密与解密的代码解析

《使用Java实现Navicat密码的加密与解密的代码解析》:本文主要介绍使用Java实现Navicat密码的加密与解密,通过本文,我们了解了如何利用Java语言实现对Navicat保存的数据库密... 目录一、背景介绍二、环境准备三、代码解析四、核心代码展示五、总结在日常开发过程中,我们有时需要处理各种软

Java List排序实例代码详解

《JavaList排序实例代码详解》:本文主要介绍JavaList排序的相关资料,Java排序方法包括自然排序、自定义排序、Lambda简化及多条件排序,实现灵活且代码简洁,文中通过代码介绍的... 目录一、自然排序二、自定义排序规则三、使用 Lambda 表达式简化 Comparator四、多条件排序五、

Java实例化对象的​7种方式详解

《Java实例化对象的​7种方式详解》在Java中,实例化对象的方式有多种,具体取决于场景需求和设计模式,本文整理了7种常用的方法,文中的示例代码讲解详细,有需要的可以了解下... 目录1. ​new 关键字(直接构造)​2. ​反射(Reflection)​​3. ​克隆(Clone)​​4. ​反序列化