在循环中创建新对象的效率 [英] Efficiency of creating new objects in a loop

查看:165
本文介绍了在循环中创建新对象的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这个问题是否与语言无关,所以我只想将其作为一个Java问题。如果你有一个循环,如

I'm not certain if this question is language independent or not so I'm going to just ask this as a Java question. If you have a loop like

for (int i = 0; i < 9; i++) {
    Object obj = new Object;
    // fill object
    // do something with data
}

循环的每次迭代都会创建内存中的新空间吗?如果是这样,旧空间是否被处理?如果没有,做这样的事情会更有效吗

Is new space in memory being created through every iteration of the loop? If so, is the old space being disposed of? If not, is it more efficient to do something like this

Object obj = new Object;
for (int i = 0; i < 9; i++) {
    // fill object
    // do something with data
}

编辑:更新代码以更好地举例说明问题

Updated code to better exemplify the question

推荐答案

简短回答:在Java开发过程中忽略这些事情,即使因为大多数这些问题都是由JVM本身黑盒子和管理的。

Short answer: just ignore such things while developing in Java, even because most of these problems are black boxed and managed by the JVM itself.

垃圾收藏家会知道该怎么做,并会根据情况尽力做到最好。

The garbage collector will know what to do and it will try to do the best thing according to the situation.

另外你的具体例子对我来说没什么意义..你能进一步详细说明吗?

In addition your specific examples don't make much sense to me.. could you elaborate it further?

这篇关于在循环中创建新对象的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆