Java – more efficient? Empty an object or create a new object?

How expensive is "new"? I mean, should I reuse the same object, or if the object is "out of range", should it be emptied?

For example, say a method to create a list:

List<Integer> list = new ArrayList<Integer>();

At the end of the method, the list is no longer used - does this mean that no memory is allocated to it, or does it mean that it has a null pointer (because it is "created")

Alternatively, I can send a "list" to the method and empty it at the end of the method: list removeAll(list); Will it be from the perspective of memory?

thank you!

Solution

It's an array list, so creating a new object means allocating a piece of memory and zeroing, plus any bookkeeping overhead Clearing the list means clearing memory This view will lead you to believe that clearing existing objects is faster However, the JVM is likely to be optimized to make memory allocation fast, so it may not be important So as long as you write clear and readable code, don't worry After all, this is Java, not C

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>