Why make short and long-lived objects a difference in garbage collection?

前端 未结 8 1889
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 19:57

I\'ve often read that in the Sun JVM short-lived objects (\"relatively new objects\") can be garbage collected more efficiently than long-lived objects (\"relatively old obj

8条回答
  •  长情又很酷
    2020-12-13 20:12

    There this phenomena that "most objects die young". Many objects are created inside a method and never stored in a field. Therefore, as soon as the method exits these objects "die" and thus are candidate for collection at the next collection cycle.

    Here is an example:

    public String concatenate(int[] arr) { 
      StringBuilder sb = new StringBuilder();
      for(int i = 0; i < arr.length; ++i)
        sb.append(i > 0 ? "," : "").append(arr[i]);
      return sb.toString();
    }
    

    The sb object will become garbage as soon as the method returns.

    By splitting the object space into two (or more) age-based areas the GC can be more efficient: instead of frequently scanning the entire heap, the GC frequently scans only the nursery (the young objects area) - which, obviously, takes much less time that a full heap scan. The older objects area is scanned less frequently.

提交回复
热议问题