Assigning “null” to objects in every application after their use

前端 未结 14 783
感动是毒
感动是毒 2021-01-18 12:05
  • Do you always assign null to an object after its scope has been reached?

  • Or do you rely on the JVM for garbage collection?

14条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 12:33

    The one time I tend to use this practice is if I need to transform a large Collection in some early part of a method.

    For example:

    public void foo() {
      List trades = loadTrades();
      Map> tradesByDate = groupTradesByDate(trades);
      trades = null; // trades no longer required.
    
      // Apply business logic to tradesByDate map.
    }
    

    Obviously I could reduce the need for this by refactoring this into another method: Map>> loadTradesAndGroupByDate() so it really depends on circumstances / clarity of code.

提交回复
热议问题