---
title: "关于 《Java 性能优化之 String 篇》 的疑问"
author: "zwhc"
date: "2012-05-18T11:55:51Z"
tags: []
categories: ["编程语言"]
slug: "java-string"
draft: false
lastmod: "2012-05-21T15:39:12Z"
id: 1534595
url: "https://zwhc.iteye.com/blog/1534595"
---

原文地址在：
http://www.ibm.com/developerworks/cn/java/j-lo-optmizestring/?cmp=dwskl&cpb=dw&ct=dwcon&cr=cn_swb&ccy=cn

文中说：
仔细观察粗体这行代码我们发现 String.substring()所返回的 String 仍然会保存原始 String, 这就是 20,000 个平均长度的单词竟然占用了上百兆的内存的原因。 一个 csv 文件中每一行都是一份很长的数据，包含了上千的单词，最后被 String.split() 或 String.substring()截取出的每一个单词仍旧包含了其原先所在的上下文中，因而导致了出乎意料的大量的内存消耗。

我对这段话比较怀疑。

String 类中的这个构造函数：

```java

 String(int offset, int count, char value[]) { 
 this.value = value; 
 this.offset = offset; 
 this.count = count; 
 } 

```


所用到的 value 应该是引用类型吧。不应该消耗内存才对。

写了段代码测试了一下：

```java

		Runtime rt = Runtime.getRuntime();
		System.out.println("maxMemory:" + rt.maxMemory());
		System.out.println("totalMemory_01:" + rt.totalMemory());

		StringBuffer sb = new StringBuffer();
		for(int i=0; i<1024*512; i++)
		{
			sb.append("0123456789");
		}
		System.out.println("totalMemory_02:" + rt.totalMemory());
		
		String s = sb.toString();
		
		//Thread.sleep(1000);
		
		String[] ss = new String[5];
		for(int i=0; i<ss.length; i++)
		{
			ss[i] = s.substring(i*11, i*11 + 13);
			System.out.println("totalMemory_03:" + rt.totalMemory());
			System.out.println("ss[i]:" + ss[i]);
			//Thread.sleep(5000);
		}

```

运行结果如下：
maxMemory:66650112
totalMemory_01:2031616
totalMemory_02:39538688
totalMemory_03:40980480
ss*:0123456789012
totalMemory_03:40980480
ss*:1234567890123
totalMemory_03:40980480
ss*:2345678901234
totalMemory_03:40980480
ss*:3456789012345
totalMemory_03:40980480
ss*:4567890123456

很明显，substring 并不会引起内存消耗增大。

===========================

前几天想了一下，原文所说的占用内存，应该是 substring 导致原始数据的字符串里的 用到的char 对象无法释放（垃圾回收）引起的。

有空我再写个程序验证一下。唔唔，这个好象不太好写。