Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

MasterMemory

> 数据库
Open source

Source Generator based Embedded Typed Readonly In-Memory Document Database for .NET and Unity.

1.8K stars0 likes0 views
WebsiteGitHub

About

Source Generator based Embedded Typed Readonly In-Memory Document Database for .NET and Unity.

MasterMemory

Source Generator based Embedded Typed Readonly In-Memory Document Database for .NET and Unity.

4700 times faster than SQLite and achieves zero allocation per query. Also the DB size is small. When SQLite is 3560kb then MasterMemory is only 222kb.

Source Generator automatically generates a typed database structure from schemas (classes), which ensures that all queries are type-safe with full autocompletion support.

This ensures both optimal performance and excellent usability.

Table of Contents

  • Concept
  • Getting Started(.NET)
  • Getting Started(Unity)
  • DataTable configuration
  • MemoryDatabase/RangeView
  • Extend Table
  • ImmutableBuilder
  • Validator
  • Metadata
  • Inheritance
  • Optimization
  • MasterMemoryGeneratorOptions
  • v2 -> v3 migration
  • License

Concept

  • Memory Efficient, Only use underlying data memory and do aggressively string interning.
  • Performance, Similar as dictionary lookup.
  • TypeSafe, 100% Type safe by Source Generator.
  • Fast load speed, MasterMemory save data by MessagePack for C#, a fastest C# serializer so load speed is blazing fast.
  • Flexible Search, Supports multiple key, multiple result, range/closest query.
  • Validator, You can define custom data validation by C#.
  • Metadata, To make custom importer/exporter, get the all database metadata.

These features are suitable for master data management(write-once, read-heavy) on embedded application, data analysis, game, etc. MasterMemory has better performance than any other database solutions. PalDB developed by LinkedIn has a similar concept(embeddable write-once key-value store), but the implementation and performance characteristics are completely different.

Getting Started(.NET)

Install the MasterMemory library(Runtime, Source Generator(Analyzer) via NuGet.

dotnet add package MasterMemory

Prepare the example table definition like following.

…

Data in MasterMemory is readonly, so it is recommended to use an immutable structure. While both records and classes are supported, records might be preferable as they generate more readable ToString methods.

MasterMemory's Source Generator detects types marked with the MemoryTable attribute and automatically generates types like the following:

Finally, you can regsiter and query by these files.

…

All table(marked by MemoryTableAttribute) and methods(created by PrimaryKeyAttribute or SecondaryKeyAttribute) are typed.

You can invoke all indexed query by IntelliSense.

Getting Started(Unity)

The minimum supported Unity version will be 2022.3.12f1, as it is necessary to support C# Incremental Source Generator(Compiler Version, 4.3.0).

Since this library is provided via NuGet, install NuGetForUnity, then navigate to Open Window from NuGet -> Manage NuGet Packages, Search "MasterMemory" and Press Install.

First, it is recommended to define assembly attributes in any cs file to enable the use of init.

csharp
// Optional: Unity can't load default namespace to Source Generator
// If not specified, 'MasterMemory' will be used by default,
// but you can use this attribute if you want to specify a different namespace.
[assembly: MasterMemoryGeneratorOptions(Namespace = "MyProj")]

// Optional: If you want to use init keyword, copy-and-paste this.
namespace System.Runtime.CompilerServices
{
    internal sealed class IsExternalInit { }
}

Everything else is the same as the standard .NET version. While the required keyword can't be used since it's from C# 11, using init alone is sufficient to guarantee immutability.

…

Also, for use with IL2CPP, you need to add the generated MasterMemoryResolver to MessagePack's Resolver. If you need other generated Resolvers, such as those from MagicOnion, please add and compose them here.

…

DataTable configuration

Element type of datatable must be marked by [MemoryTable(tableName)], datatable is generated from marked type. string tableName is saved in database binary, you can rename class name if tableName is same.

[PrimaryKey(keyOrder = 0)], [SecondaryKey(indexNo, keyOrder)], [NonUnique] can add to public property, [PrimaryKey] must use in MemoryTable, [SecondaryKey] is option.

Both PrimaryKey and SecondaryKey can add to multiple properties, it will be generated ***And***And***.... keyOrder is order of column names, default is zero(sequential in which they appear).

csharp
[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
    [PrimaryKey]
    public int Foo { get; set; }
    [PrimaryKey]
    public int Bar { get; set; }
}

db.Sample.FindByFooAndBar((int Foo, int Bar))

// ----

[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
    [PrimaryKey(keyOrder: 1)]
    public int Foo { get; set; }
    [PrimaryKey(keyOrder: 0)]
    public int Bar { get; set; }
}

db.Sample.FindByBarAndFoo((int Bar, int Foo))

Default of FindBy*** return type is single(if not found, returns null). It means key is unique by default. If mark [NonUnique] in same AttributeList, return type is RangeView<T>(if not found, return empty).

csharp
[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
    [PrimaryKey, NonUnique]
    public int Foo { get; set; }
    [PrimaryKey, NonUnique]
    public int Bar { get; set; }
}

RangeView<Sample> q = db.Sample.FindByFooAndBar((int Foo, int Bar))
csharp
[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
    [PrimaryKey]
    [SecondaryKey(0)]
    public int Foo { get; set; }
    [SecondaryKey(0)]
    [SecondaryKey(1)]
    public int Bar { get; set; }
}

db.Sample.FindByFoo(int Foo)
db.Sample.FindByFooAndBar((int Foo, int Bar))
db.Sample.FindByBar(int Bar)

[StringComparisonOption] allow to configure how compare if key is string. Default is Ordinal.

csharp
[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
    [PrimaryKey]
    [StringComparisonOption(StringComparison.InvariantCultureIgnoreCase)]
    public string Foo { get; set; }
}

If computation property exists, add [IgnoreMember] of MessagePack should mark.

csharp
[MemoryTable("person"), MessagePackObject(true)]
public class Person
{
    [PrimaryKey]
    public int Id { get;}

    public string FirstName { get; }
    public string LastName { get; }

    [IgnoreMember]
    public string FullName => FirstName + LastName;
}

MemoryDatabase/RangeView

In default, MemoryDatabase do all string data automatically interning(see: Wikipedia/String interning). If multiple same string value exists in database(ex: "goblin","goblin", "goblin", "goblin", "goblin"....), standard database creates string value per query or store multiple same values. But MasterMemory stores single string value reference, it can save much memory if data is denormalized.

Use intern or not is selected in constructor. If you want to disable automatically interning, use internString:false.

MemoryDatabase(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1).

MemoryDatabase has three(or four) query methods.

  • T|RangeView<T> FindBy***(TKey key)
  • bool TryFindBy***(TKey key, out T result)
  • T|RangeView<T> FindClosestBy***(TKey key, bool selectLower = true)
  • RangeView<T> FindRangeBy***(TKey min, TKey max, bool ascendant = true)

If index key is unique, generates FindBy*** and TryFindBy*** methods and then FindBy*** throws KeyNotFoundException when key is not found.

By*** is generated by PrimaryKey and SecondaryKey defines.

And has some utility properties.

  • int Count
  • RangeView<T> All
  • RangeView<T> AllReverse
  • RangeView<T> SortBy***
  • T[] GetRawDataUnsafe()

struct RangeView<T> : IEnumerable<T> is the view of database elements. It has following property/method.

  • T [int index]
  • int Count
  • T First
  • T Last
  • RangeView<T> Reverse
  • IEnumerator<T> GetEnumerator()

Extend Table

Generated table class is defined partial class so create same namespace and class name's partial class on another file, you can add your custom method to generated table.

Table class also defined partial OnAfterConstruct method, it called after table has been constructed. You can use it to store custom data to field after all data has been constructed.

…

ImmutableBuilder

If you want to add/modify data to loaded database, you can use ToImmutableBuilder method.

csharp
// Create ImmutableBuilder from original database.
var builder = db.ToImmutableBuilder();

// Add Or Replace compare with PrimaryKey
builder.Diff(addOrReplaceData);

// Remove by PrimaryKey
builder.RemovePerson(new[] { 1, 10, 100 });

// Replace all data
builder.ReplaceAll(newData);

// Finally create new database
MemoryDatabase newDatabase = builder.Build();

// If you want to save new database, you can convert to MemoryDatabase->DatabaseBuilder
var newBuilder = newDatabase.ToDatabaseBuilder();
var newBinary = newBuilder.Build(); // or use WriteToStream

MemoryDatabase's reference can use as snapshot.

csharp
// 1 game per 1 instance
public class GameRoom
{
    MemoryDatabase database;

    // The reference is a snapshot of the timing of game begins.
    public GameRoom(MemoryDatabase database)
    {
        this.database = database;
    }
}

Validator

You can validate data by MemoryDatabase.Validate method. In default, it check unique key(data duplicated) and you can define custom validate logics.

…

Following is list of validation methods.

…

Metadata

You can get the table-info, properties, indexes by metadata api. It helps to make custom importer/exporter application.

csharp
var metaDb = MemoryDatabase.GetMetaDatabase();
foreach (var table in metaDb.GetTableInfos())
{
    // for example, generate CSV header
    var sb = new StringBuilder();
    foreach (var prop in table.Properties)
    {
        if (sb.Length != 0) sb.Append(",");

        // Name can convert to LowerCamelCase or SnakeCase.
        sb.Append(prop.NameSnakeCase);
    }
    File.WriteAllText(table.TableName + ".csv", sb.ToString(), new UTF8Encoding(false));
}

If creates console-app, our ConsoleAppFramework can easy to make helper applications.

Here is sample of reading and creating dynamic from csv. builder.AppendDynamic and System.Runtime.Serialization.FormatterServices.GetUninitializedObject will help it.

…

Inheritance

Currently MasterMemory does not support inheritance. Recommend way to create common method, use interface and extension method. But if you want to create common method with common cached field(made by OnAfterConstruct), for workaround, create abstract class and all data properties to abstract.

…

Optimization

When invoking new MemoryDatabase(byte[] databaseBinary...), read and construct database from binary. If binary size is large then construct performance will slow down. MemoryDatabase has ctor(..., int maxDegreeOfParallelism = 1) option in constructor to construct in parallel.

csharp
var database = new MemoryDatabase(bin, maxDegreeOfParallelism: Environment.ProcessorCount);

The use of Parallel can greatly improve the construct performance. Recommend to use `Env

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#c-sharpmemory-databaseunity

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库