java - for循环中创建对象
迷茫
迷茫 2017-04-17 17:42:37
0
11
1549

下面这两种for循环中新建对象写法有什么区别呢?
第一种:

list<User> users = new ArrayList<User>();
User user = null;
for (int i = 0; i < 10; i++) {
    user = new User();
    user.setUserId(i);
    user.setUserName("segment" + i);
    users.add(user);
}
……

第二种:

list<User> users = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
    User user = new User();
    user.setUserId(i);
    user.setUserName("segment" + i);
    users.add(user);
}
……

这两种写法对集合users中的内容有影响吗,还是只是性能上有区别?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(11)
迷茫

No impact, just the scope of the user variable is different.
If you need to do special processing on the last value of the loop, use the first form; otherwise, I think the second form is better.

巴扎黑

A new object is created every time it loops, and each object is different. There is no difference between the two ways of writing

大家讲道理

Everything is fine. No difference

Peter_Zhu
list<User> users = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
    users.add(new User().setUserId(i).setUserName("segment" + i));
}
左手右手慢动作

Personally, there seems to be no difference..

黄舟

Maybe the first one has better performance, but this is not a problem that Java programmers consider at all. Intuitively speaking, the second one has better coding standards and readability.

迷茫

It seems that the first method creates one more object, and the rest has no effect

洪涛

Remember one principle: variables should be declared and created only when needed. So: the second one, but the difference is small. Those students who say there is a difference in efficiency hope to have data to support it and show it to everyone

洪涛

The content has no impact. It is the first type. After the for loop ends, the user still points to a piece of memory that will not be recycled by the garbage collector.

迷茫

Basically no difference. The only difference is that the reference counter adjustment timing is slightly different, but the object is always referenced, and even the GC will not be triggered. So this one really makes no difference.
For objects declared in the loop body, marking the object will release the reference after the scope ends. However, if it is declared outside the loop, the previous reference will not be released until the next assignment. Even if it is not saved by the container, under JAVA's GC mechanism, there is not much difference. The object will not be released until the next GC trip.

Considering the readability of the code, if the object is used within the loop body, do not declare it outside. When the scope is large and the code complexity is high, it is easy to make errors.
Still the same principle: create when needed.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!