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

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

    It depends on how costly the object is, both in terms of initialization required and how large it's memory footprint is. It also depends heavily on the kind of application (what else does the application spend time on).

    For your example with the ArrayList, its already very hard to give a definite answer - depending on how many entries there are in the list, clear() can be very expensive or very cheap, while a new ArrayList has almost constant cost.

    The general rule of thumb is: Don't bother with reusing objects until you have measured that you have a performance problem, and then be very sure that creating the objects is the cause of that problem. Most likely there are more rewarding optimization opportunities in your application. A profiler will help identify the places where you spend the most time. Focus on those and better algoryhtms.

提交回复
热议问题