Skip to content

Memory leak using EmbedHostObject #65

@ralfkahlert

Description

@ralfkahlert

Accessing properties of registered host objects leak memory

The following examples registers a tiny host object with one property and one basic method within. Using a docker runtime with 128MB, memory will grow quickly and process will die after about 100000 calls reaching its memory limit. If the method doSomething is moved up to the class Native, everything works fine and the process stays at stable 27MB memory usage.

using System;
using JavaScriptEngineSwitcher.ChakraCore;
using JavaScriptEngineSwitcher.Core;

public class Native {
    public SomeClass SomeObject { get; set; } = new SomeClass();
}

public class SomeClass {
    public string doSomething(double i) => "SomeValue@" + i;
}

class Program
{
    static void Main(string[] args)
    {
        var newEngine = new ChakraCoreJsEngine();

        newEngine.EmbedHostObject("native", new Native());
        newEngine.Execute(@"function testFunction(i) {
                                return native.SomeObject.doSomething(i);
                            }");

        for (int i=0; i < 1000000; i++) {
            var result = newEngine.CallFunction("testFunction", new object[] { (double)i });
            if (i % 10000 == 0) Console.WriteLine($"Called test #{i}, result was {result}");
        }
    }
}

In this simple example we can work around the leak pre-evaluating the property.

        newEngine.EmbedHostObject("_native", new Native());
        newEngine.Execute(@"var native = { SomeObject: _native.SomeObject };");

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions