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

前端 未结 6 914
北恋
北恋 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:56

    I don't know much about memory footprints in java, but I think emptying a List to reuse it, is not such a good idea because of the performance impact of emptying the List. And I think it is also in an OO perspective not a good idea, because you should have one object with just one purpose.

    At the end of a method the object is indeed out of scope. But that doesn't mean it is garbage collected or even eligible for garbage collection, because others might still reference that List. So basically: if there are no objects references to that List then it might be elegible for garbage collection, but if it will be garbage collected it still unsure, if the List is still stored in the Young Generation space it can either be in the Eden space or Tenured space. Eden space is where objects are first allocated, when garbage collection happens and the object is still alive it will be moved to survivor space. If it still survives past that it will move on to the Tenured space, where I believe not much garbage collection happens. But all this depends how long an object lives, who refers to this object and where it is allocated

提交回复
热议问题