Skip to content

Automatic memory management

Wang Renxin edited this page Jul 28, 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 automatic memory management is an important part for a dynamic language.

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, such as: collections, class instance and referenced usertype, etc. A referenced value maintains a reference count, the initialized count value is 1 when it's created, 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 1 (none referencing).

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 1 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 for later disposing. 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 configure GC in MY-BASIC, for more information read the Customize macros page.

Clone this wiki locally