Skip to content

Memory leak using UInt8Array #370

@simontom

Description

@simontom

Hey guys,
would u mind looking at this sky high rocketing unmanaged memory allocations which are not getting GC'ed?

We found this is happening since v7.1.5 (GC works like a charm in v7.1.4).
Happening on the latest version, too.

Repro (according to this issue):

using Microsoft.ClearScript.JavaScript;
using Microsoft.ClearScript.V8;

namespace V8EngineWorkbench;

internal static class Program
{
    private const int Size = 4096;
    private static readonly byte[] Bytes = CreateBytes();

    private static void Main()
    {
        for (var repetitions = 0; repetitions < 16; repetitions++)
        {
            CreateLeak();
        }
    }

    private static void CreateLeak()
    {
        var engine = new V8ScriptEngine();

        dynamic uint8ArrayFactoryFunc = engine.Evaluate(@"
            (function (length) {
                return new Uint8Array(length);
            })
            .valueOf();
        ");

        ITypedArray<byte> Alloc(long byteCount) => uint8ArrayFactoryFunc(byteCount);

        for (var i = 0; i < 10_000; i++)
        {
            var typedArray = Alloc(Size);
            typedArray.Write(Bytes, 0, Size, 0);
        }

        // engine.CollectGarbage(true); // Not helping
        engine.Dispose();
    }

    private static void CreateLeak2()
    {
        var engine = new V8ScriptEngine();

        engine.AddHostType(typeof(Task));

        engine.Execute(@"
            (async function () {
                for (let i = 0; i < 160_000; i++) {
                    const newData = new Uint8Array(4096);
                    newData.fill(42);

                    await Task.Delay(1);
                }
            })();
        ");

        engine.Dispose();
    }

    private static byte[] CreateBytes()
    {
        var bytes = new byte[Size];
        Array.Fill(bytes, (byte)42);
        return bytes;
    }
}

If u look at the CreateLeak2, all the data stays in the Engine and the result is the same.

Process memory profile from dotMemory on v7.1.5:
image

Process memory profile from dotMemory on v7.1.4:
image

Tested on:

  • ClearScript v7.1.4 (this one works pretty fine), v7.1.5, v7.2.3, v7.2.4
  • .Net 6

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions