| |
很简单的一个例子: 不要使用 string ts=new string(“hello”); 这样会生成多余的对象. 最好使用 string ts=”hello”; //add by chris: 很多文章都建议使用stringbuffer来代替string,为什么会带来性能的提高哪?这里有篇文章:http://www.matrix.org.cn/article_view.asp?id=67 为了理解深入点,我们看一个例子: string s1 = "testing string"; string s2 = "concatenation performance"; string s3 = s1 + " " + s2; 另外一种方法: stringbuffer s = new stringbuffer(); s.append("testing string"); s.append(" "); s.append("concatenation performance"); string s3 = s.tostring(); 在上面这个例子里面,其实性能是没有提高的,为什么会这样哪? 这个在这里就不讨论了。有兴趣请研究一下stringbuffer的源代码。 //end of add
其实在jvm里面,如果你下一次再构造一个值为”hello”的对象string,jvm可以重用以前的对象的。 而且不要在循环或者多次调用的地方新建一个对象,一定要尽量避免这个
|
|