Baby’s First Garbage Collector › 标记清除 Marking and sweeping [#265]

很多不同的方法可以实现查找和回收所有未使用对象的过程,但为此发明的最简单且第一个发明的算法称为“标记清除”。它是由 Lisp 和大胡子的发明者约翰·麦卡锡(John McCarthy)发明的,所以今天实现这个算法有点像与一位远古之神交流,希望不是以某种洛夫克拉夫特式的方式,否则你的思想和视网膜最终会被炸得一干二净。
There are a bunch of different ways (https://en.wikipedia.org/wiki/Tracing_garbage_collection) you can implement the process of finding and reclaiming all of the unused objects, but the simplest and first algorithm ever invented for it is called “mark-sweep”. It was invented by John McCarthy, the man who invented Lisp and beards, so implementing today is like communing with one of the Elder Gods, but hopefully not in some Lovecraftian way that ends with you having your mind and retinas blasted clean.

该算法的工作原理几乎与我们对可达性的定义完全相同:
  1. 从根开始,遍历整个对象图。每次到达一个对象时,将其上的“标记”位设置为 true。
  2. 完成后,找到所有未设置标记位的对象将其删除。
The algorithm works almost exactly like our definition of reachability:
  1. Starting at the roots, traverse the entire object graph. Every time you reach an object, set a “mark” bit on it to true.
  2. Once that’s done, find all of the objects whose mark bits are not set and delete them.

就是这样。我知道,你本来可以想出这个的,对吧?如果你这么做了,你就会成为一篇被引用数百次的论文的作者。这件事给我们的教训是,要在 CS 领域出名,你不必想出真正晦涩难懂的东西,你只需首先想出明显的东西即可。
That’s it. I know, you could have come up with that, right? If you had, you’d be the author of a paper cited hundreds of times. The lesson here is that to be famous in CS, you don’t have to come up with really obscure stuff, you just have to come up with obvious stuff first.