Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instance.GetFunction Cache #294

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions src/Instance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,12 @@ public Instance(Store store, Module module, params object[] imports)
/// <returns>Returns the function if a function of that name was exported or null if not.</returns>
public Function? GetFunction(string name)
{
lock (_functionCache)
{
if (_functionCache.TryGetValue(name, out var func))
return func;
}

var context = _store.Context;
if (!TryGetExtern(context, name, out var ext) || ext.kind != ExternKind.Func)
{
Expand All @@ -524,7 +530,13 @@ public Instance(Store store, Module module, params object[] imports)

GC.KeepAlive(_store);

return _store.GetCachedExtern(ext.of.func);
var result = _store.GetCachedExtern(ext.of.func);
lock (_functionCache)
{
_functionCache[name] = result;
}

return result;
}

/// <summary>
Expand Down Expand Up @@ -552,14 +564,26 @@ public Instance(Store store, Module module, params object[] imports)
/// <returns>Returns the memory if a memory of that name was exported or null if not.</returns>
public Memory? GetMemory(string name)
{
lock (_memoryCache)
{
if (_memoryCache.TryGetValue(name, out var memory))
return memory;
}

if (!TryGetExtern(_store.Context, name, out var ext) || ext.kind != ExternKind.Memory)
{
return null;
}

GC.KeepAlive(_store);

return _store.GetCachedExtern(ext.of.memory);
var result = _store.GetCachedExtern(ext.of.memory);
lock (_memoryCache)
{
_memoryCache[name] = result;
}

return result;
}

/// <summary>
Expand Down Expand Up @@ -715,5 +739,8 @@ private static class Native

private readonly Store _store;
internal readonly ExternInstance instance;

private readonly Dictionary<string, Function?> _functionCache = new();
private readonly Dictionary<string, Memory?> _memoryCache = new();
}
}
Loading