MasterMemory 4.0.0
dotnet add package MasterMemory --version 4.0.0
NuGet\Install-Package MasterMemory -Version 4.0.0
<PackageReference Include="MasterMemory" Version="4.0.0" />
<PackageVersion Include="MasterMemory" Version="4.0.0" />
<PackageReference Include="MasterMemory" />
paket add MasterMemory --version 4.0.0
#r "nuget: MasterMemory, 4.0.0"
#:package MasterMemory@4.0.0
#addin nuget:?package=MasterMemory&version=4.0.0
#tool nuget:?package=MasterMemory&version=4.0.0
MasterMemory
Source Generator based Embedded Typed Readonly In-Memory Document Database for .NET and Unity(safe with Native AOT and IL2CPP).

MasterMemory lookups are zero-allocation and 1900 times faster than SQLite with its default settings.
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.
Concept
- Memory Efficient, Only use underlying data memory and do aggressively string interning.
- Performance, Similar as dictionary lookup, don't allocate per query.
- TypeSafe, 100% Type safe by Source Generator.
- Fast load speed, MasterMemory save data by MessagePack for C# 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.
Getting Started
Install the MasterMemory library (the runtime and the Source Generator (Analyzer) in one package) via NuGet.
dotnet add package MasterMemory
Prepare the example table definition like following.
public enum Gender
{
Male, Female, Unknown
}
// table definition marked by MemoryTableAttribute.
// database-table must be serializable by MessagePack-CSharp
[MemoryTable("person"), MessagePackObject]
public record Person
{
// index definition by attributes.
[PrimaryKey]
[Key(0)]
public required int PersonId { get; init; }
// secondary index can add multiple(discriminated by index-number).
[SecondaryKey(0), NonUnique]
[SecondaryKey(1, keyOrder: 1), NonUnique]
[Key(1)]
public required int Age { get; init; }
[SecondaryKey(2), NonUnique]
[SecondaryKey(1, keyOrder: 0), NonUnique]
[Key(2)]
public required Gender Gender { get; init; }
[Key(3)]
public required string Name { get; init; }
}
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 register and query by these files.
using ...; // Your project default namespace
// to create database, use DatabaseBuilder and Append method.
var builder = new DatabaseBuilder();
builder.Append(new Person[]
{
new (){ PersonId = 0, Age = 13, Gender = Gender.Male, Name = "Dana Terry" },
new (){ PersonId = 1, Age = 17, Gender = Gender.Male, Name = "Kirk Obrien" },
new (){ PersonId = 2, Age = 31, Gender = Gender.Male, Name = "Wm Banks" },
new (){ PersonId = 3, Age = 44, Gender = Gender.Male, Name = "Karl Benson" },
new (){ PersonId = 4, Age = 23, Gender = Gender.Male, Name = "Jared Holland" },
new (){ PersonId = 5, Age = 27, Gender = Gender.Female, Name = "Jeanne Phelps" },
new (){ PersonId = 6, Age = 25, Gender = Gender.Female, Name = "Willie Rose" },
new (){ PersonId = 7, Age = 11, Gender = Gender.Female, Name = "Shari Gutierrez" },
new (){ PersonId = 8, Age = 63, Gender = Gender.Female, Name = "Lori Wilson" },
new (){ PersonId = 9, Age = 34, Gender = Gender.Female, Name = "Lena Ramsey" },
});
// build database binary(you can also use `WriteToStream` for save to file).
byte[] data = builder.Build();
// -----------------------
// for query phase, create MemoryDatabase.
// (MemoryDatabase is recommended to store in singleton container(static field/DI)).
var db = new MemoryDatabase(data);
// .PersonTable.FindByPersonId is fully typed by code-generation.
Person person = db.PersonTable.FindByPersonId(5);
// Multiple key is also typed, Return value is multiple if key is marked with `NonUnique`.
RangeView<Person> result = db.PersonTable.FindByGenderAndAge(Gender.Female, 23);
// Get nearest value(choose lower(default) or higher).
RangeView<Person> age1 = db.PersonTable.FindClosestByAge(31);
// Get range(min-max inclusive).
RangeView<Person> age2 = db.PersonTable.FindRangeByAge(20, 29);
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.
// 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.
MessagePackFormatterFactory.DefaultAot is used by default. If your tables contain types that need their own formatters (the UnityEngine value types, for example), pass the factory that serves them:
// Vector3 and friends: the MessagePack.Unity package
var options = new MemoryDatabaseOptions { FormatterFactory = MessagePackFormatterFactory.DefaultAot.WithUnity() };
var bin = new DatabaseBuilder(options).Append(data).Build();
var db = new MemoryDatabase(bin, options);
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).
[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
[PrimaryKey]
public int Foo { get; set; }
[PrimaryKey]
public int Bar { get; set; }
}
db.SampleTable.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.SampleTable.FindByBarAndFoo(int Bar, int Foo)
The leading part of a composite key can be queried on its own. For example, an index on (Gender, Age) generates not only FindByGenderAndAge but also FindByGender and FindRangeByGender. This applies to both PrimaryKey and SecondaryKey.
[MemoryTable("person"), MessagePackObject(true)]
public class Person
{
[PrimaryKey]
public int PersonId { get; set; }
[SecondaryKey(0, keyOrder: 0), NonUnique]
public Gender Gender { get; set; }
[SecondaryKey(0, keyOrder: 1), NonUnique]
public int Age { get; set; }
}
RangeView<Person> a = db.PersonTable.FindByGenderAndAge(Gender.Female, 23);
RangeView<Person> b = db.PersonTable.FindByGender(Gender.Female); // every Female, in order of Age
RangeView<Person> c = db.PersonTable.FindRangeByGender(Gender.Male, Gender.Female);
By default, FindBy*** returns a single element and throws KeyNotFoundException if the key is not found. Keys are unique by default. For a key that may be missing, use TryFindBy***, which returns false instead of throwing. If marked with [NonUnique] in the same AttributeList, the return type is RangeView<T> (empty if not found). The rows of one key come in the order of the primary key; rows that share a [NonUnique] primary key come in the order they were given to the builder.
[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.SampleTable.FindByFooAndBar(int Foo, int Bar)
[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.SampleTable.FindByFoo(int Foo)
db.SampleTable.FindByFooAndBar(int Foo, int Bar)
db.SampleTable.FindByBar(int Bar)
[StringComparisonOption] allow to configure how compare if key is string. Default is Ordinal. The option belongs to the property: it holds in every key the property is a member of, a composite key included, and it may be written in any attribute list of the property. A composite key is compared member by member, each string by its own option.
[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
[PrimaryKey]
[StringComparisonOption(StringComparison.InvariantCultureIgnoreCase)]
public string Foo { get; set; }
}
[MemoryTable("sample"), MessagePackObject(true)]
public class Sample
{
[PrimaryKey(0), StringComparisonOption(StringComparison.OrdinalIgnoreCase)]
public string Foo { get; set; } // ignoring case
[PrimaryKey(1)]
public string Bar { get; set; } // ordinal
}
A table is stored in the database binary in the order of its primary key, and the same order is used to search it when it is loaded. Ordinal and OrdinalIgnoreCase are the same on every machine; the culture options depend on the culture and its data on the machine that builds and on the device that loads, so prefer the ordinal ones for a primary key.
If computation property exists, add [IgnoreMember] of MessagePack should mark.
[MemoryTable("person"), MessagePackObject(true)]
public class Person
{
[PrimaryKey]
public int Id { get; init; }
public string FirstName { get; init; }
public string LastName { get; init; }
[IgnoreMember]
public string FullName => FirstName + LastName;
}
MemoryDatabase/MemoryDatabaseOptions
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.
How a database is read is said by MemoryDatabaseOptions, which is optional: new MemoryDatabase(bin) reads with options that say nothing, new MemoryDatabaseOptions(), made for that database.
public sealed record MemoryDatabaseOptions
{
public bool InternString { get; init; } = true;
public MessagePackFormatterFactory? FormatterFactory { get; init; } = null; // null: MessagePackFormatterFactory.DefaultAot
public MessagePackMessageProcessor? MessageProcessor { get; init; } = null; // null: the tables are not compressed
public void ClearInternedStrings();
}
// make the options once, and give the same ones to the database and to the builder
static readonly MemoryDatabaseOptions options = new MemoryDatabaseOptions();
var db = new MemoryDatabase(bin, options);
var builder = new DatabaseBuilder(options);
InternString: if you want to disable automatically interning, set it to false.ClearInternedStrings()empties the pool of interned strings. The databases that were read keep their strings, and the formatters made for the options stay.FormatterFactorysupplies the formatters of the table types and their members. The default isMessagePackFormatterFactory.DefaultAot(source-generated and built-in formatters only, the same on the JIT as under IL2CPP and Native AOT); you can also specify your own formatter factory chain if needed.MessageProcessoris what the tables are compressed with; the default leaves them as they are, see "Optimization and Compression".
The options hold what MessagePack has made for the formatters, and the pool of interned strings, which is why they are worth making once and keeping: a second database or builder with the same options makes neither again.
MemoryDatabase(byte[]|ReadOnlyMemory<byte>|ReadOnlySpan<byte> databaseBinary, MemoryDatabaseOptions options = null, int maxDegreeOfParallelism = 1).
The database binary can be passed as byte[], ReadOnlyMemory<byte> or ReadOnlySpan<byte>. Setting maxDegreeOfParallelism parallelizes the initialization of the database (deserializing the binary into the in-memory database) per table, which makes it faster (not available for ReadOnlySpan<byte>). Environment.ProcessorCount is a good value.
The binary is read until the constructor returns and is not kept, so the buffer can be reused or released right after.
RangeView
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)
If index key is unique, generates FindBy*** and TryFindBy*** methods and then FindBy*** throws KeyNotFoundException when key is not found. TryFindBy*** is for a key that may be missing: it is the same search, returns false and throws nothing.
By*** is generated by PrimaryKey and SecondaryKey defines.
And has some utility properties.
intCountRangeView<T>AllReverseRangeView<T>AllReverseRangeView<T>SortBy***T[] GetRawDataUnsafe()
struct RangeView<T> is the view of database elements: rows that lie together in an index, in the order of that index. It is a window on the array of the index and copies nothing. It has following property/method.
T[int index]intCountTFirstTLastT?FirstOrDefault()T?LastOrDefault()boolAny()ReadOnlySpan<T>AsSpan()T[]ToArray()IReadOnlyList<T>AsReadOnlyList()ReverseRangeView<T>ReverseEnumeratorGetEnumerator()
Reverse is the same rows from the last to the first. It is a type of its own, struct ReverseRangeView<T>, with the same members except AsSpan() (a span runs one way only), and its Reverse is the RangeView<T> again. AllReverse of a table is one, too.
RangeView<Person> twenties = db.PersonTable.FindRangeByAge(20, 29); // in order of Age
ReverseRangeView<Person> oldestFirst = twenties.Reverse; // the same rows, the other way
ReadOnlySpan<Person> span = twenties.AsSpan(); // the rows as a span of the index
Person? youngest = twenties.FirstOrDefault(); // null when there is none
foreach (var person in twenties) { } // no allocation
// LINQ, and anything else that takes an IEnumerable<T>, goes through AsReadOnlyList()
string[] names = twenties.AsReadOnlyList().Where(x => x.Gender == Gender.Female).Select(x => x.Name).ToArray();
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.
// create MonsterTable.Partial.cs
public sealed partial class MonsterTable
{
int maxHp;
#pragma warning disable CS0649
readonly int minHp;
#pragma warning restore CS0649
// called after constructed
partial void OnAfterConstruct()
{
// a table is constructed for every database, empty for one that does not have it: Max() of nothing throws
if (Count == 0) return;
maxHp = All.AsReadOnlyList().Select(x => x.MaxHp).Max();
// you can use Unsafe.AsRef to set readonly field
Unsafe.AsRef(minHp) = All.AsReadOnlyList().Select(x => x.MaxHp).Min();
}
// add custom method other than standard Find method
public IEnumerable<Monster> GetRangedMonster(int arg1)
{
return All.AsReadOnlyList().Where....();
}
}
DatabaseBuilder
Use DatabaseBuilder to create a database. Build() or WriteToStream() generates the binary data to save. ToMemoryDatabase() converts the builder directly into a MemoryDatabase, and ToDatabaseBuilder converts a MemoryDatabase back into a builder.
var builder = new DatabaseBuilder()
.Append(persons)
.Append(items);
// the database binary, to save and to ship
byte[] bin = builder.Build();
// or the database, with no binary in between
MemoryDatabase db = builder.ToMemoryDatabase();
// make the builder from database
DatabaseBuilder builder2 = db.ToDatabaseBuilder();
ToMemoryDatabase serializes nothing, which makes it the short way for tests, tools and editor code, for example to Validate() rows before their binary is written.
If you want to add/modify data to loaded database, make a builder from it with ToDatabaseBuilder. The builder starts with every table of the database, and the database itself is never changed. This can be used for things like differential updates of a database.
// Create DatabaseBuilder from original database.
var builder = db.ToDatabaseBuilder();
// Add Or Replace compare with PrimaryKey
builder.AddOrReplace(addOrReplaceData);
// Remove by PrimaryKey
builder.RemovePerson(1, 10, 100);
// Replace all data
builder.ReplaceAll(newData);
// Finally create new database, tables that were not changed are shared with the original
MemoryDatabase newDatabase = builder.ToMemoryDatabase();
// If you want to save new database, the same builder writes it
var newBinary = builder.Build(); // or use WriteToStream
Appendis for a table the builder does not have yet and throws for one it has.AddOrReplaceandRemove***are generated for tables whose primary key is unique.AddOrReplacetakes its rows in order: of two rows with one key, the later one stays.Remove***takes a composite key as a tuple:builder.RemoveSkill((1, 2), (3, 1)).- A builder from
ToDatabaseBuilderwrites the way the database was read: with the same formatters, and compressed if the database was.db.ToDatabaseBuilder(options)writes with other options.
MemoryDatabase's reference can use as snapshot.
// 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.
// Implements IValidatable<T> to targeted validation
[MemoryTable("quest_master"), MessagePackObject(true)]
public class Quest : IValidatable<Quest>
{
// If index is Unique, validate duplicate in default.
[PrimaryKey]
public int Id { get; init; }
public string Name { get; init; }
public int RewardId { get; init; }
public int Cost { get; init; }
void IValidatable<Quest>.Validate(IValidator<Quest> validator)
{
// get the external reference table
var items = validator.GetReferenceSet<Item>();
// Custom if logics.
if (this.RewardId > 0)
{
// RewardId must exists in Item.ItemId
items.Exists(x => x.RewardId, x => x.ItemId);
}
// Range check, Cost must be 10..20
validator.Validate(x => x.Cost >= 10);
validator.Validate(x => x.Cost <= 20);
// In this region, only called once so enable to validate overall of tables.
if (validator.CallOnce())
{
var quests = validator.GetTableSet();
// Check unique other than index property.
quests.Where(x => x.RewardId != 0).Unique(x => x.RewardId);
}
}
}
[MemoryTable("item_master"), MessagePackObject(true)]
public class Item
{
[PrimaryKey]
public int ItemId { get; init; }
}
void Main()
{
var db = new MemoryDatabase(bin);
// Get the validate result.
var validateResult = db.Validate();
if (validateResult.IsValidationFailed)
{
// Output string format.
Console.WriteLine(validateResult.FormatFailedResults());
// Get the raw FaildItem[]. (.Type, .Message, .Data)
// validateResult.FailedResults
}
}
Following is list of validation methods.
// all void methods are assert function, it stores message to ValidateResult if failed.
interface IValidator<T>
{
ValidatableSet<T> GetTableSet();
ReferenceSet<T, TRef> GetReferenceSet<TRef>();
void Validate(Expression<Func<T, bool>> predicate);
void Validate(Func<T, bool> predicate, string message);
void ValidateAction(Expression<Func<bool>> predicate);
void ValidateAction(Func<bool> predicate, string message);
void Fail(string message);
bool CallOnce();
}
class ReferenceSet<TElement, TReference>
{
IReadOnlyList<TReference> TableData { get; }
void Exists<TProperty>(Expression<Func<TElement, TProperty>> elementSelector, Expression<Func<TReference, TProperty>> referenceElementSelector);
void Exists<TProperty>(Expression<Func<TElement, TProperty>> elementSelector, Expression<Func<TReference, TProperty>> referenceElementSelector, EqualityComparer<TProperty> equalityComparer);
}
class ValidatableSet<TElement>
{
IReadOnlyList<TElement> TableData { get; }
void Unique<TProperty>(Expression<Func<TElement, TProperty>> selector);
void Unique<TProperty>(Expression<Func<TElement, TProperty>> selector, IEqualityComparer<TProperty> equalityComparer);
void Unique<TProperty>(Func<TElement, TProperty> selector, string message);
void Unique<TProperty>(Func<TElement, TProperty> selector, IEqualityComparer<TProperty> equalityComparer, string message);
void Sequential(Expression<Func<TElement, SByte|Int16|Int32|...>> selector, bool distinct = false);
void Sequential(Func<TElement, SByte|Int16|Int32|...> selector, string message, bool distinct = false);
ValidatableSet<TElement> Where(Func<TElement, bool> predicate);
}
Metadata
You can get the table-info, properties, indexes by metadata api. It helps to make custom importer/exporter application.
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.CompilerServices.RuntimeHelpers.GetUninitializedObject will help it.
var csv = @"monster_id,name,max_hp
1,foo,100
2,bar,200";
var fileName = "monster";
var builder = new DatabaseBuilder();
var meta = MemoryDatabase.GetMetaDatabase();
var table = meta.GetTableInfo(fileName);
var tableData = new List<object>();
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(csv)))
using (var sr = new StreamReader(ms, Encoding.UTF8))
using (var reader = new TinyCsvReader(sr))
{
while ((reader.ReadValuesWithHeader() is Dictionary<string, string> values))
{
// create data without call constructor
// (on .NET Framework, where RuntimeHelpers does not have it: System.Runtime.Serialization.FormatterServices.GetUninitializedObject)
var data = System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(table.DataType);
foreach (var prop in table.Properties)
{
if (values.TryGetValue(prop.NameSnakeCase, out var rawValue))
{
var value = ParseValue(prop.PropertyInfo.PropertyType, rawValue);
if (prop.PropertyInfo.SetMethod == null)
{
throw new Exception("Target property does not exists set method. If you use {get;}, please change to { get; init; }, Type:" + prop.PropertyInfo.DeclaringType + " Prop:" + prop.PropertyInfo.Name);
}
prop.PropertyInfo.SetValue(data, value);
}
else
{
throw new KeyNotFoundException($"Not found \"{prop.NameSnakeCase}\" in \"{fileName}.csv\" header.");
}
}
tableData.Add(data);
}
}
// add dynamic collection.
builder.AppendDynamic(table.DataType, tableData);
var bin = builder.Build();
var database = new MemoryDatabase(bin);
static object ParseValue(Type type, string rawValue)
{
if (type == typeof(string)) return rawValue;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (string.IsNullOrWhiteSpace(rawValue)) return null;
return ParseValue(type.GenericTypeArguments[0], rawValue);
}
if (type.IsEnum)
{
var value = Enum.Parse(type, rawValue);
return value;
}
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
// True/False or 0,1
if (int.TryParse(rawValue, out var intBool))
{
return Convert.ToBoolean(intBool);
}
return Boolean.Parse(rawValue);
case TypeCode.Char:
return Char.Parse(rawValue);
case TypeCode.SByte:
return SByte.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.Byte:
return Byte.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.Int16:
return Int16.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.UInt16:
return UInt16.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.Int32:
return Int32.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.UInt32:
return UInt32.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.Int64:
return Int64.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.UInt64:
return UInt64.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.Single:
return Single.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.Double:
return Double.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.Decimal:
return Decimal.Parse(rawValue, CultureInfo.InvariantCulture);
case TypeCode.DateTime:
return DateTime.Parse(rawValue, CultureInfo.InvariantCulture);
default:
if (type == typeof(DateTimeOffset))
{
return DateTimeOffset.Parse(rawValue, CultureInfo.InvariantCulture);
}
else if (type == typeof(TimeSpan))
{
return TimeSpan.Parse(rawValue, CultureInfo.InvariantCulture);
}
else if (type == typeof(Guid))
{
return Guid.Parse(rawValue);
}
// or other your custom parsing.
throw new NotSupportedException();
}
}
// Non string escape, tiny reader with header.
public class TinyCsvReader : IDisposable
{
static char[] trim = new[] { ' ', '\t' };
readonly StreamReader reader;
public IReadOnlyList<string> Header { get; private set; }
public TinyCsvReader(StreamReader reader)
{
this.reader = reader;
{
var line = reader.ReadLine();
if (line == null) throw new InvalidOperationException("Header is null.");
var index = 0;
var header = new List<string>();
while (index < line.Length)
{
var s = GetValue(line, ref index);
if (s.Length == 0) break;
header.Add(s);
}
this.Header = header;
}
}
string GetValue(string line, ref int i)
{
var temp = new char[line.Length - i];
var j = 0;
for (; i < line.Length; i++)
{
if (line[i] == ',')
{
i += 1;
break;
}
temp[j++] = line[i];
}
return new string(temp, 0, j).Trim(trim);
}
public string[] ReadValues()
{
var line = reader.ReadLine();
if (line == null) return null;
if (string.IsNullOrWhiteSpace(line)) return null;
var values = new string[Header.Count];
var lineIndex = 0;
for (int i = 0; i < values.Length; i++)
{
var s = GetValue(line, ref lineIndex);
values[i] = s;
}
return values;
}
public Dictionary<string, string> ReadValuesWithHeader()
{
var values = ReadValues();
if (values == null) return null;
var dict = new Dictionary<string, string>();
for (int i = 0; i < values.Length; i++)
{
dict.Add(Header[i], values[i]);
}
return dict;
}
public void Dispose()
{
reader.Dispose();
}
}
}
MasterMemoryGeneratorOptions
The Source Generator settings are configured using the assembly attribute [MasterMemoryGeneratorOptions]. By placing it in any file, you can configure the following settings.
[assembly: MasterMemoryGeneratorOptions(
Namespace = "MyConsoleApp",
PrefixClassName = "Foo",
GenerateMetaDatabase = false,
GenerateValidator = false
)]
Namespace: Changes the namespace of generated files. If not specified, it tries to get theRootNamespaceset in the csproj file; if that's not available, it defaults toMasterMemoryPrefixClassName: Adds a prefix to the class names of generated files. For example,DatabaseBuilderbecomesFooDatabaseBuilder. This allows you to distinguish between multiple MasterMemory projects by name.GenerateMetaDatabase: By default (true),MemoryDatabase.GetMetaDatabase()and theCreateMetaTable()of every table are generated, see "Metadata". If set to false they are not, which makes the generated code smaller where nothing reads the metadataGenerateValidator: By default (true),MemoryDatabase.Validate()is generated, see "Validator". If set to false it is not, and theValidatemethods of yourIValidatable<T>classes are called by nothingReduceMemoryUsage: By default (false), an index whose key has no string in it keeps the keys of its rows in an array of their own, which makes its lookups faster and takes memory, see "Key arrays". If set to true no index has such an array: the tables take less memory and their lookups are slower
A client application that only reads the database often needs neither the metadata nor the validator. For example in Unity, to generate them only in the editor and leave them out of the application, configure it like this to reduce the binary size.
[assembly: MasterMemoryGeneratorOptions(
#if !UNITY_EDITOR
GenerateMetaDatabase = false,
GenerateValidator = false,
#endif
Namespace = "MyConsoleApp",
PrefixClassName = "Foo"
)]
Inheritance
A table class can have a base class. The properties of the base class are data of the table like its own, and a key declared there is a key of the table, so tables that have members in common can share them, and the methods written over them:
public abstract class FooAndBarBase
{
[PrimaryKey]
public int Prop1 { get; init; }
public int Prop2 { get; init; }
[IgnoreMember]
public int Prop3 => Prop1 + Prop2;
public IEnumerable<FooAndBarBase> CommonMethod()
{
throw new NotImplementedException();
}
}
[MemoryTable("foo_table"), MessagePackObject(true)]
public class FooTable : FooAndBarBase
{
// a key of this table alone, beside the one of the base class
[SecondaryKey(0), NonUnique]
public int Level { get; init; }
}
[MemoryTable("bar_table"), MessagePackObject(true)]
public class BarTable : FooAndBarBase
{
public int Floors { get; init; }
}
Each class marked [MemoryTable] is a table of its own: db.FooTableTable and db.BarTableTable here, each with FindByProp1.
Optimization and Compression
Query speed after a MemoryDatabase is constructed is the same either way, but load speed and database size depend on the serialization format of MessagePack. With [MessagePackObject(true)] every row carries the name of every member; with [MessagePackObject] and [Key(0)], [Key(1)], ... a row is an array of its values. Measured on 10,000 made-up rows of each kind.
| Rows | Member names | + LZ4 | Integer keys | + LZ4 | Read, member names | Read, integer keys |
|---|---|---|---|---|---|---|
| numbers: 18 columns | 1,980 KB | 623 KB | 486 KB | 395 KB | 1.11 ms | 0.61 ms |
| text: id, key, speaker, body | 2,350 KB | 1,259 KB | 2,155 KB | 1,251 KB | 1.25 ms | 1.20 ms |
A database is stored as serialized arrays of objects. With member names as keys ([MessagePackObject(true)]) the names are repeated in every row and the binary gets large. Such data compresses very well with LZ4 though, so adding LZ4 compression shrinks it considerably.
Even so, integer keys ([Key(0)], [Key(1)], ...) are smaller than that, and much faster to load. Adding Key to every member takes some effort in the table definitions, but integer keys without compression are what we recommend most.
Compression is effective with string keys, or when the tables contain a lot of strings. In that case MasterMemory recommends LZ4, which is fast to decompress. It is provided by MessagePack for C#, so it is easy to enable. Nothing is compressed by default.
// dotnet add package MessagePack.LZ4
var options = new MemoryDatabaseOptions { MessageProcessor = new Lz4BlockProcessor() };
var bin = new DatabaseBuilder(options).Append(data).Build();
var db = new MemoryDatabase(bin, options);
To use LZ4, install the MessagePack.LZ4 package separately. It uses an external package, NativeCompressions, so using it in Unity also requires the NativeCompressions.Unity package. See the NativeCompressions README for details.
Key arrays
A lookup is a binary search. Searching the rows reads one object for every step, each wherever it is in memory, and that is what a lookup in a large database spends its time on. So an index whose key holds no reference (a number, an enum, DateTime, Guid, a nullable of those, or a composite key of those; not a string) keeps the keys of its rows in an array beside them. Its lookups search that array, which lies together in memory, and read a row only once it is found.
Measured on x64 (.NET 10) with rows of about 220 bytes, in nanoseconds per FindBy***:
| Key | Tables | ReduceMemoryUsage = true |
Default |
|---|---|---|---|
int |
one of 1,000 rows, looked up in a loop | 18 | 15 |
int |
one of 100,000 rows, looked up in a loop | 133 | 71 |
int |
one of 1,000,000 rows, looked up in a loop | 507 | 142 |
int |
1,000 of 1,000 rows each, another table every time | 401 | 111 |
long |
1,000 of 1,000 rows each, another table every time | 271 | 96 |
(int, int) |
1,000 of 1,000 rows each, another table every time | 251 | 125 |
int, 10 rows a key |
1,000 of 1,000 rows each, another table every time | 230 | 105 |
TryFindBy***, FindClosestBy*** and FindRangeBy*** search the same array. A key with a string in it has no array and is searched in the rows, as fast as before.
The array takes the size of the key for every row of the index: 4 bytes for an int, 8 for a long or an (int, int). For the table above, with five such indexes, that was 28 bytes a row, an eighth more memory. Loading a database takes the same time. A unique primary key of one integer whose values run without a gap (1, 2, 3, ...) is read at its position without a search, and has no array.
Where memory matters more than the speed of lookups, turn the arrays off for the whole assembly:
[assembly: MasterMemoryGeneratorOptions(ReduceMemoryUsage = true)]
v3 → v4 migration
MasterMemory v4 runs on MessagePack for C# v4. The database binary format is unchanged: v4 reads a database built by v3. However, v3 compressed tables with LZ4 by default, so to read a v3 database, v4 needs the LZ4 processor to be specified explicitly.
A composite key is now passed member by member, not as a tuple. FindByGenderAndAge((Gender.Female, 23)) becomes FindByGenderAndAge(Gender.Female, 23), and the same goes for TryFindBy*** and FindClosestBy***. FindRangeBy*** takes the members of min, then the members of max. These calls become plain compile errors, so an LLM should be able to fix them all at once without trouble.
- Tables are not compressed by default. To read a v3 database, install
MessagePack.LZ4and passnew MemoryDatabaseOptions { MessageProcessor = new Lz4BlockProcessor() }. See "Optimization and Compression". - Constructor arguments moved to
MemoryDatabaseOptions:new MemoryDatabase(bin, internString: false)becomesnew MemoryDatabase(bin, new MemoryDatabaseOptions { InternString = false }), and anIFormatterResolverargument becomes theFormatterFactoryof the options. MasterMemoryResolveris no longer generated. Remove its registration (StaticCompositeResolver,MessagePackSerializer.DefaultOptions); nothing replaces it.- The default formatters are
MessagePackFormatterFactory.DefaultAot. If a table has a type without a source-generated formatter, setFormatterFactory = MessagePackFormatterFactory.Default. - Table types follow the rules of MessagePack for C# v4, see Migrating from v3.
IsReturnNullIfKeyNotFoundis removed, andFindBy***always throwsKeyNotFoundExceptionfor a missing key. ReplaceFindBy***and a null check withTryFindBy***(key, out var row). The null checks still compile, so look for them yourself.FindRangeBy***(min, max, ascendant: false)becomesFindRangeBy***(min, max).Reverse. A reversed view is aReverseRangeView<T>.RangeView<T>no longer implementsIEnumerable<T>andIReadOnlyList<T>. For LINQ, callAsReadOnlyList():FindByGender(gender).AsReadOnlyList().Where(...).ImmutableBuilderis removed, useDatabaseBuilder:db.ToImmutableBuilder()becomesdb.ToDatabaseBuilder(),Diff(rows)becomesAddOrReplace(rows), andBuild()becomesToMemoryDatabase().- The
MemoryDatabaseconstructor that takes tables is removed. UseDatabaseBuilder.ToMemoryDatabase(). - The
DISABLE_MASTERMEMORY_METADATABASEandDISABLE_MASTERMEMORY_VALIDATORsymbols are no longer read. SetGenerateMetaDatabase = falseandGenerateValidator = falsein[MasterMemoryGeneratorOptions]. TableInfo.DumpAsJson(MessagePackSerializerOptions)becomesDumpAsJson(MemoryDatabaseOptions).- The
MasterMemory.Annotationspackage is no longer needed: the attributes are inMasterMemory. Remove the reference. - String keys are always compared by
Ordinal, or by their[StringComparisonOption]. v3 compared astring?key and a string in a composite key by the current culture, and ignored a[StringComparisonOption]written before the key attribute. v4 reads such a v3 database, but rebuild it with v4; a v3 client cannot read one built by v4 correctly. - An index whose key has no string in it now keeps its keys in an array of their own: lookups are faster, and each such index takes the size of its key more memory for every row (4 bytes for an
int).ReduceMemoryUsage = truein[MasterMemoryGeneratorOptions]turns that off. See "Key arrays". - The leading part of a composite key now has generated lookups (
FindByGenderfor a(Gender, Age)key). If you wrote a method with the same name in a partial table class, remove yours.
v2 → v3 migration
Since there are no changes to the API, binary format, or behavior, you can migrate simply by changing the command-line tool settings to the assembly attribute [MasterMemoryGeneratorOptions].
- The code generator (MSBuild Task, .NET Core Global/Local Tools) has been removed and replaced with Source Generator
- Tool options are now available through
MasterMemoryGeneratorOptions(e.g.-usingNamespace) - The
-addImmutableConstructoroption has been completely removed; please use C#'s record or init keyword instead - The library is now only available through NuGet for Unity. Please use NuGetForUnity
License
This library is under the MIT License.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 is compatible. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- MessagePack (>= 4.0.0)
-
.NETStandard 2.1
- MessagePack (>= 4.0.0)
-
net9.0
- MessagePack (>= 4.0.0)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on MasterMemory:
| Package | Downloads |
|---|---|
|
MasterMemory.Annotations
Migration shim for MasterMemory v3 code: the attributes now live in the MasterMemory package and this package type-forwards to it. Reference MasterMemory directly in new projects. |
|
|
JpPublicHolidays
内閣府ホームページで公開されている「国民の祝日」CSVファイルを扱うためのライブラリです。 |
|
|
MasterMemorySplint
Package Description |
|
|
AndanteTribe.MasterSystem
Master data converter for MasterSystem. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.0.0 | 0 | 12/4/2026 |
| 3.0.4 | 319,038 | 6/12/2025 |
| 3.0.3 | 60,896 | 1/9/2025 |
| 3.0.2 | 1,033 | 1/8/2025 |
| 3.0.1 | 18,230 | 12/20/2024 |
| 3.0.0 | 383 | 12/20/2024 |
| 2.4.4 | 2,560,707 | 5/27/2022 |
| 2.4.3 | 9,280 | 3/3/2022 |
| 2.4.1 | 1,110 | 2/16/2022 |
| 2.4.0 | 835 | 2/16/2022 |
| 2.3.5 | 97,077 | 5/19/2021 |
| 2.3.4 | 7,589 | 12/9/2020 |
| 2.3.3 | 3,859 | 9/10/2020 |
| 2.3.2 | 1,126 | 8/11/2020 |
| 2.3.1 | 2,325 | 6/15/2020 |
| 2.3.0 | 977 | 6/15/2020 |
| 2.2.2 | 1,671 | 4/3/2020 |
| 2.2.1 | 959 | 3/25/2020 |
| 2.2.0 | 944 | 3/25/2020 |
| 2.1.2 | 20,294 | 3/11/2020 |