看板java
标 题Re: [问题] 初学者的几点小疑问
发信站SayYA 资讯站 (Thu Apr 19 11:12:55 2007)
转信站ptt!ctu-reader!news.nctu!SayYa
※ 引述《qrtt1 (foolish)》之铭言:
> : 因为小弟刚接触java(自修) 如果觉得问题太蠢还请见谅
> : 问题1:为何n1==n2(结果:false)而i1==i2(结果:true) 他们的值不是都相等吗?
> : 还是Integer oo = new Integer (xx) 与 Integer oo = xx 二种方式有哪不同吗?
> : 问题2: 那又为啥同样是 Integer oo = xx 的方式
> : i1==i2(ture) 而p1==p2(false) 这又是为啥?我只不过数字修正了一下
> 这是 autoboxing & unboxing 的功能,
> 至於为什麽改了数字就不一样了,
> 因为 autoboxing 後在某一段会做 value cached
> (减轻产生物件的 cost)
> http://java.sun.com/developer/JDCTechTips/2005/tt0405.html
> <%
> Autoboxing is guaranteed to return the same object for integral values in the
> range [-128, 127], but an implementation may, at its discretion, cache values
> outside of that range. It would be bad style to rely on this caching in your
> code.
> %>
> 不过上面的值域会依变数型态不同而不同,但还是以 jvm 实作的为准
> http://javaonnet.blogspot.com/
> <%
> Advantage of autoboxing and auto-unboxing is concise code. But careless use
> might result in poor performance of the code. Certain primitives are cached
> and autoboxing returns same wrapper objects. This value may depend on jvm
> used, normally this value are:
> 1. The boolean values true and false.
> 2. The byte values.
> 3. The short and int values between -128 and 127.
> 4. The char values in the range '\u0000' to '\u007F'.
> %>
> 其实再挖挖,有人在讨论这倒底是不是一个 bad style !?
> http://forum.java.sun.com/thread.jspa?forumID=316&threadID=536731
> (解决了旧问题,产生了新问题)
题底出来了原来是物件简并的手法以重复使用物件减少GC来提昇程式效能
import java.util.Random;
public class Test1 {
final private Random r = new Random();
public int getNumber() {
int i = r.nextInt(127);
if (r.nextBoolean())
i = i * -1;
return i;
}
public void testNew() {
int c = 9999999;
while (c-- >0) {
// 不使用简并
new Integer(getNumber());
try {
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void testValueOf() {
int c = 9999999;
while (c-- >0) {
// 使用简并
Integer.valueOf((getNumber()));
try {
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Test1().testValueOf();
//new Test1().testNew();
}
}
ValueOf (简并 --> reuse)
http://farm1.static.flickr.com/210/464703162_82ca5ff60b_o.jpg
New (无简并 --> no reuse)
http://farm1.static.flickr.com/229/464703070_51bb9346a3_o.jpg
--
我们都不知道,那些我们不知道的事情,我们就是不知道。
--
我们都不知道,那些我们不知道的事情,我们就是不知道。
--
※ Origin: SayYA 资讯站 <bbs.sayya.org>
◆ From: 211.21.79.162