what's more efficient? to empty an object or create a new one?

前端 未结 6 831
北恋
北恋 2021-02-05 23:07

how expensive is \'new\'? I mean, should I aim at reusing the same object or if the object is \'out of scope\' it\'s the same as emptying it?

example, say a method crea

6条回答
  •  清酒与你
    2021-02-05 23:47

    at the end of the method the list is no longer in use - does it mean that there's no memory allocated to it anymore or does it mean that there's a null pointer to it (since it was 'created').

    Means there are no references to it and object is eligible for GC.

    Alternately, I can send a 'list' to the method and empty it at the end of the method with: list.removeAll(list); will that make any difference from memory point of view?

    It's tradeoff between time/space. Removing elements from list is time consuming, even though you don't need to create new objects.

    With the latest JVMs GC collection capabilities, it is ok to create new object WHEN REQUIRED (but avoiding object creation in loop is best). Longer references to an object sometimes make that object NOT eligible for GC and may cause memory leak if not handled properly.

提交回复
热议问题