Memory Management

DWScript simplifies development by managing the lifecycle of script objects automatically. It uses a hybrid approach to ensure both performance and safety.

Automatic Reference Counting (ARC)

The primary mechanism for memory management is ARC. Every time an object is assigned to a variable or passed as a parameter, its reference count increases. When the variable goes out of scope, the count decreases.

When the count reaches zero, the object is immediately destroyed and its destructor is called. This provides deterministic cleanup for resources like file handles or database connections.

Cycle Detection (Garbage Collection)

A common issue with pure ARC is "circular references" (e.g., Object A points to B, and B points back to A), which prevents reference counts from ever reaching zero.

DWScript includes a Garbage Collector (GC) that periodically scans for these isolated "islands" of objects. If an island is unreachable from the rest of the script, the GC will break the cycles and free the memory.

Manual Control

While automation is the default, you can still exercise manual control when necessary.

  • Free: You can call obj.Free to immediately trigger the destructor. Unlike some other environments, calling Free does not set the reference to nil. Instead, the object is marked as destroyed. Any subsequent attempt to access the object's fields or methods will trigger an Object already destroyed exception.

Memory Safety

Because of these mechanisms, DWScript is largely immune to common memory errors found in languages with manual management:

  • Memory Leaks: Automated by ARC and the Cycle Collector.
  • Use After Free: Safely caught by the runtime. If you access an object after it has been freed, the script will throw an exception rather than causing a crash or memory corruption.
  • Double Free: Calling Free on an already destroyed object is safely handled.
On this page