What are the benefits to using WeakReferences?

前端 未结 4 626
暗喜
暗喜 2020-12-25 08:21

I have some memory leaks in my app. They all originate around a specific view cluster that I have spent a loooot of time tweaking and trying to reduce a much contextual pass

4条回答
  •  自闭症患者
    2020-12-25 08:58

    I don't think this is the right solution to your problem. As others have said, if you use WeakReferences you make your code more expensive and more fragile. The fragility occurs because each time you use the weak reference you could potentially get an exception.

    (Another issue is that WeakReferences are more expensive than regular references for the GC to deal with. I don't have any actual performance numbers to hand, and this is most likely irrelevant in your use-case, but this at least a theoretical concern.)

    IMO, a better approach to your problem is to use a good memory profiler to track down where the memory leaks are actually occurring and fix it. Run the application for a bit using a memory profiler, identify some object that has leaked, and use the profiler to trace the path or paths by which the object is still reachable. You will probably find that this can be traced back to one or two bugs, or the same bug pattern repeated in a few places. (My guess would be event listeners that are not removed at the right time.)

提交回复
热议问题