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

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

    For small lists, it is probably a bit cheaper cheaper to clear() the list.

    For the asymptotic case of really large lists in a really large heap, it boils down to whether the GC can zero a large chunk of memory faster than the for loop in clear() can. And I think it probably can.

    However, my advice would be to ignore this unless you have convincing evidence (from profiling) that you have a high turn-over of ArrayList objects. (It is a bad idea to optimize based solely on your intuition.)

提交回复
热议问题