循环中的不可变对象创建

时间:2015-05-03 20:48:05

标签: java garbage-collection immutability

根据我的理解,在循环中创建可变对象,就像下面的方法一样,会创建一堆对象,垃圾收集必须处理每个新对象。

for (int i=0; i<1000000000; i++){
    Object obj = new Object();
}

与重用同一对象但不需要垃圾回收的方法相反。

Object obj;
for (int i=0; i<1000000000; i++){
    obj = new Object();
}

但是当使用在实例化后无法更改的不可变对象时呢?无论如何,垃圾收集仍然必须在这些对象上运行,对吗?如果是这样,那么在这种情况下,这些方法中的任何一个在垃圾收集和性能方面都有所不同吗?

比如说对象是BigDecimal:

for (int i=0; i<1000000000; i++){
    BigDecimal number = new BigDecimal(someValue);
}

VS

BigDecimal number;
for (int i=0; i<1000000000; i++){
    number = new BigDecimal(someValue);
}

现在我们正在处理不可变对象,这两者有什么不同吗?...除了范围,我知道这两个例子的范围不同。谢谢!

1 个答案:

答案 0 :(得分:1)

  

与重用同一对象但不需要垃圾回收的方法相反。

不,您描述的每个场景都会创建需要收集垃圾的对象。

  

现在我们正在处理不可变对象,这两者有什么不同吗?

没有。虽然VM可以缓存一些不可变对象,例如Integervoid mygc() { //int **max = (int **) 0xbfffffffUL; // the address of the top of the stack unsigned long stack_bottom; int **max = (int **) GC_init(); // get the address of the bottom of the stack int* q; int **p = &q; // the address of the bottom of the stack while (p < max) { //printf("0. p: %u, *p: %u max: %u\n",p,*p,max); mark(*p); p++; } //utilize sweep and coalesce (coalesce function already written) } void mark(int *p) { int i; int *ptr; //code here } void sweep(int *ptr) { // code here } int *isPtr(int *p) { //return the pointer or NULL int *ptr = start; //code here } 类型。

相关问题