Skip to content

Automatic memory management

Wang Renxin edited this page Mar 3, 2016 · 7 revisions

MY-BASIC uses both Reference Counting and Garbage Collection to manage memory automatically. It's necessary to introduce these techniques to MY-BASIC while memory disposing is a big business.

Some data types such as Integer, Real, etc. are value types that it copies the value directly when assigning a value to another, and it disposes the old value when assigning with a new one.

Besides, MY-BASIC supports referenced data types as well: Collections and Referenced Usertype. A referenced value maintains a reference count, the reference count increases by 1 when it's referenced by another object, and decreases by 1 when unreferenced by an object; objects referencing the same value share the raw value instead of copying it, MY-BASIC disposes the value when the reference count reaches 0.

Reference counting solved most automatic disposing issues, on the other hand it brings a new referenced cycle issue; for instance two values reference each other but not referenced by other values, the reference counts of them never reach 0 which will cause memory leak. So as a supplement to reference counting I added garbage collection to MY-BASIC. MY-BASIC does a mark-sweep GC algorithm when unreferencing operation occurred exact times; it iterates all referenced values from the root scope to detect unreachable values to dispose them. It solves leakage properly.

For example:

k = list() ' k references a list
l = list() ' l references a list
push(l, k) ' l references k
push(k, l) ' k references l, got a cycle
k = nil    ' unreference the list value of k
l = nil    ' unreference the list value of l

It won't generate leakage in MY-BASIC.

It's able to customize GC in MY-BASIC, for more information read the Customize macros page.

Clone this wiki locally