How to reduce the number of objects created in Scala?

后端 未结 5 1645
余生分开走
余生分开走 2021-02-08 03:24

I\'m programming a computer graphics application in Scala which uses a RGB class to return the color at a point in the image. As you can imagine, the function which return the c

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 04:04

    Your question #3 wasn't addressed yet so I will give it a shot.

    How does the GC know that I'm throwing [short lived objects] away quickly?

    The working of modern GCs is based on the observation that objects of different lifetime behave very differently. So it manages them in so called generations. Objects just created are stored in the eden space. When this fills up, all the objects in it which are still being referenced by (i.e. they are alive) get copied over to the so called young generation space. Thus all dead objects are left behind and the space occupied by them reclaimed with practically zero effort. This is what makes short lived objects so cheap for the JVM. And most of the objects created by an average program are temporary or local variables which fall out of scope very quickly.

    After this first round of GC, the young generation space(s) are managed in a similar fashion, except that there may be more of them. The GC can be configured to have the objects spend one or more rounds in the young generation space(s). Then eventually, the final survivors are migrated into the survivor (aka old generation) space, where they are to stay for the rest of their lifetime. This space is managed by periodically applying some variant of the classical mark and sweep technique: walk through the graph of all live references and mark live objects, then sweep out all unmarked (dead) objects by compacting the survivors into one contiguous memory block, thus defragmenting free memory. This is an expensive operation which blocks the execution of the program, and it is very difficult to implement it correctly, especially in a modern multithreaded VM. This is why generational GC was invented, to ensure that only a tiny fraction of all objects created get to this stage.

提交回复
热议问题