AutolangDocs
Optimization Notes

Constructor Optimization

Understanding how the VM instantiates classes enables you to write highly optimized code. Learn to separate dynamic logic from static heap allocations.

Primary vs. Secondary Constructors

Autolang optimizes class instantiation at the bytecode level depending on how properties are defined inside constructors.

Secondary Constructor (Slow)

Executes multiple SET_FIELD instructions sequentially. Each assignment creates instruction evaluation overhead within the core VM loop.

Primary Constructor (Bulk Copy)

Triggers a single native bulk-copy. The VM maps fields to contiguous slots in memory and allocates the entire object layout in a single pass.

Pseudo-constructors Pattern

To maintain fast bulk copies while supporting complex init logic, define static methods acting as constructor entry points.

class Player(val id: Int, val health: Float, val name: String) { // High-Speed Primary Constructor storage layout static fun Player(name: String): Player { // Complex computations happen here val generatedId = 0 val defaultHealth = 100.0 // Triggers the primary constructor block copy return Player(generatedId, defaultHealth, name) } } // Both initializations trigger the static factory pseudo-constructor val p1 = Player.Player("Alice") val p2 = Player("Bob") println("Player: " + p1.name)

Why this is faster:

Traditional constructors perform operations followed by multiple sequential this.field = field allocations. By isolating dynamic logic inside a static function and returning a Primary Constructor call, the VM only performs a single-pass native copy.

Native Bindings & Generics

Pseudo-constructors enable native classes (written in C++) and generic wrappers to pass internal configurations cleanly to the VM backend.

@no_extends @no_constructor class Map<K, V> { // __CLASS__ is replaced with "Map" at compile time. // Calling Map<String, Int>() triggers this native function. @native("map_constructor") static fun __CLASS__() : Map<K,V> = <K, V>{} } // Instantiates map with bound generic types passed to C++ heap val myMap = Map<String, Int>()
⚙️

Native Type Identifiers

The getClassId(K) compiler macro evaluates at compile time, passing the exact type integer ID to the C++ heap. This enables typed native generic allocation (like std/json and std/map).