Skip to content

Unclear way to free memory that was allocated by new #230

@kyasbal

Description

@kyasbal

Hi, I think it is very important to write about this topic explicitly.


class Vector2{
   public x:u32;

   public y:u32;
}

When you created such a class shown above, you may use new keyword to create an instance like the code below.

for(let i:u32 = 0; i < 10000000; i++){
   let v = new Vector2();
   // Some of code using vector2 here
}

However, AssemblyScript has no GC feature at this point, the v allocated for each loop iteration will not be released. You can confirm this phenomenon with inspecting exports.memory.buffer.byteLength from javascript. To remove class instance explicitly like C++ languages, AssemblyScript require you to write release code explicitly.

This can be done with memory.free method. This method receive a pointer to release. We can retrive a pointer to the instance by calling changeType<usize>(instance).

for(let i:u32 = 0; i < 10000000; i++){
   let v = new Vector2();
   // Some of code using vector2 here
   memory.free(changeType<usize>(v));
}

I don't think this way is so clear since the memory.free can't receive class instance variable directly. Even that, it is very hard to notice how it shoud be done.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions