• Stars
    star
    1,314
  • Rank 35,801 (Top 0.8 %)
  • Language
    C#
  • License
    MIT License
  • Created over 5 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Fast .NET C# Implementation of ULID for .NET and Unity.

Ulid

GitHub Actions Releases

Fast C# Implementation of ULID for .NET Core and Unity. Ulid is sortable, random id generator. This project aims performance by fastest binary serializer(MessagePack-CSharp) technology. It achives faster generate than Guid.NewGuid.

image

NuGet: Ulid or download .unitypackage from Ulid/Releases page.

Install-Package Ulid

Table of Contents

How to use

Similar api to Guid.

  • Ulid.NewUlid()
  • Ulid.Parse()
  • Ulid.TryParse()
  • new Ulid()
  • .ToString()
  • .ToByteArray()
  • .TryWriteBytes()
  • .TryWriteStringify()
  • .ToBase64()
  • .Time
  • .Random

Performance

Guid is standard corelib guid. Ulid is this library. NUlid is competitor RobThree/NUlid.

  • New
Method Mean Error Ratio Gen 0/1k Op Gen 1/1k Op Gen 2/1k Op Allocated Memory/Op
Guid_ 73.13 ns NA 1.00 - - - -
Ulid_ 65.41 ns NA 0.89 - - - -
NUlid_ 209.89 ns NA 2.87 0.0162 - - 104 B

Ulid.NewUlid() is faster than Guid.NewGuid() and zero allocation.

  • Parse
Method Mean Error Ratio Gen 0/1k Op Gen 1/1k Op Gen 2/1k Op Allocated Memory/Op
Guid_ 197.98 ns NA 1.00 - - - -
Ulid_ 28.67 ns NA 0.14 - - - -
NUlid_ 161.03 ns NA 0.81 0.0441 - - 280 B

from string(Base32) to ulid, Ulid.Parse(string) is fastest and zero allocation.

  • ToString
Method Mean Error Ratio Gen 0/1k Op Gen 1/1k Op Gen 2/1k Op Allocated Memory/Op
Guid_ 57.73 ns NA 1.00 0.0163 - - 104 B
Ulid_ 38.77 ns NA 0.67 0.0126 - - 80 B
NUlid_ 96.76 ns NA 1.68 0.0583 - - 368 B

to string representation(Base32), Ulid.ToString() is fastest and less allocation.

  • NewId().ToString()
Method Mean Error Ratio Gen 0/1k Op Gen 1/1k Op Gen 2/1k Op Allocated Memory/Op
Guid_ 205.7 ns NA 1.00 0.0162 - - 104 B
Ulid_ 110.2 ns NA 0.54 0.0125 - - 80 B
NUlid_ 301.7 ns NA 1.47 0.0744 - - 472 B

case of get the string representation immediately, Ulid is twice faster than Guid.

  • GetHashCode
Method Mean Error Ratio Gen 0/1k Op Gen 1/1k Op Gen 2/1k Op Allocated Memory/Op
Guid_ 0.9706 ns NA 1.00 - - - -
Ulid_ 1.0329 ns NA 1.06 - - - -
NUlid_ 20.6175 ns NA 21.24 0.0063 - - 40 B

GetHashCode is called when use dictionary's key. Ulid is fast and zero allocation.

  • Equals
Method Mean Error Ratio Gen 0/1k Op Gen 1/1k Op Gen 2/1k Op Allocated Memory/Op
Guid_ 1.819 ns NA 1.00 - - - -
Ulid_ 2.023 ns NA 1.11 - - - -
NUlid_ 29.875 ns NA 16.43 0.0126 - - 80 B

Equals is called when use dictionary's key. Ulid is fast and zero allocation.

  • CompareTo
Method Mean Error Ratio Gen 0/1k Op Gen 1/1k Op Gen 2/1k Op Allocated Memory/Op
Guid_ 5.409 ns NA 1.00 - - - -
Ulid_ 3.838 ns NA 0.71 - - - -
NUlid_ 17.126 ns NA 3.17 0.0063 - - 40 B

CompareTo is called when use sort. Ulid is fastest and zero allocation.

Cli

You can install command-line to generate ulid string by .NET Core Global Tool.

dotnet tool install --global ulid-cli

after installed, you can call like here.

$ dotnet ulid
01D7CB31YQKCJPY9FDTN2WTAFF

$ dotnet ulid -t "2019/03/25" -min
01D6R3EBC00000000000000000

$ dotnet ulid -t "2019/03/25" -max
01D6R3EBC0ZZZZZZZZZZZZZZZZ

$ dotnet ulid -t "2019/03/25" -max -base64
AWmwNy2A/////////////w==
argument list:
-t, -timestamp: [default=null]timestamp(converted to UTC, ISO8601 format recommended)
-r, -randomness: [default=null]randomness bytes(formatted as Base32, must be 16 characters, case insensitive)
-b, -base64: [default=False]output as base64 format, or output base32 if false
-min, -minRandomness: [default=False]min-randomness(use 000...)
-max, -maxRandomness: [default=False]max-randomness(use ZZZ...)

This CLI tool is powered by ConsoleAppFramework.

Integrate

System.Text.Json

NuGet: Ulid.SystemTextJson

You can use custom Ulid converter - Cysharp.Serialization.Json.UlidJsonConverter.

var options = new JsonSerializerOptions()
{
    Converters =
    {
        new Cysharp.Serialization.Json.UlidJsonConverter()
    }
};

JsonSerializer.Serialize(Ulid.NewUlid(), options);

If application targetframework is netcoreapp3.0, converter is builtin, does not require to add Ulid.SystemTextJson package, and does not require use custom options.

MessagePack-CSharp

NuGet: Ulid.MessagePack

You can use custom Ulid formatter - Cysharp.Serialization.MessagePack.UlidMessagePackFormatter and resolver - Cysharp.Serialization.MessagePack.UlidMessagePackResolver.

var resolver = MessagePack.Resolvers.CompositeResolver.Create(
    Cysharp.Serialization.MessagePack.UlidMessagePackResolver.Instance,
    MessagePack.Resolvers.StandardResolver.Instance);
var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);

MessagePackSerializer.Serialize(Ulid.NewUlid(), options);

If you want to use this custom formatter on Unity, download UlidMessagePackFormatter.cs.

Dapper

For Dapper or other ADO.NET database mapper, register custom converter from Ulid to binary or Ulid to string.

public class BinaryUlidHandler : TypeHandler<Ulid>
{
    public override Ulid Parse(object value)
    {
        return new Ulid((byte[])value);
    }

    public override void SetValue(IDbDataParameter parameter, Ulid value)
    {
        parameter.DbType = DbType.Binary;
        parameter.Size = 16;
        parameter.Value = value.ToByteArray();
    }
}

public class StringUlidHandler : TypeHandler<Ulid>
{
    public override Ulid Parse(object value)
    {
        return Ulid.Parse((string)value);
    }

    public override void SetValue(IDbDataParameter parameter, Ulid value)
    {
        parameter.DbType = DbType.StringFixedLength;
        parameter.Size = 26;
        parameter.Value = value.ToString();
    }
}

// setup handler
Dapper.SqlMapper.AddTypeHandler(new BinaryUlidHandler());

Entity Framework Core

to use in EF, create ValueConverter and bind it.

public class UlidToBytesConverter : ValueConverter<Ulid, byte[]>
{
    private static readonly ConverterMappingHints defaultHints = new ConverterMappingHints(size: 16);

    public UlidToBytesConverter(ConverterMappingHints mappingHints = null)
        : base(
                convertToProviderExpression: x => x.ToByteArray(),
                convertFromProviderExpression: x => new Ulid(x),
                mappingHints: defaultHints.With(mappingHints))
    {
    }
}

public class UlidToStringConverter : ValueConverter<Ulid, string>
{
    private static readonly ConverterMappingHints defaultHints = new ConverterMappingHints(size: 26);

    public UlidToStringConverter(ConverterMappingHints mappingHints = null)
        : base(
                convertToProviderExpression: x => x.ToString(),
                convertFromProviderExpression: x => Ulid.Parse(x),
                mappingHints: defaultHints.With(mappingHints))
    {
    }
}

License

This library is under the MIT License.

More Repositories

1

UniTask

Provides an efficient allocation free async/await integration for Unity.
C#
8,201
star
2

MagicOnion

Unified Realtime/API framework for .NET platform and Unity.
C#
3,838
star
3

MemoryPack

Zero encoding extreme performance binary serializer for C# and Unity.
C#
3,288
star
4

R3

The new future of dotnet/reactive and UniRx.
C#
2,177
star
5

ZString

Zero Allocation StringBuilder for .NET and Unity.
C#
2,060
star
6

ConsoleAppFramework

Zero Dependency, Zero Overhead, Zero Reflection, Zero Allocation, AOT Safe CLI Framework powered by C# Source Generator.
C#
1,635
star
7

MasterMemory

Embedded Typed Readonly In-Memory Document Database for .NET and Unity.
C#
1,521
star
8

MessagePipe

High performance in-memory/distributed messaging pipeline for .NET and Unity.
C#
1,406
star
9

ZLogger

Zero Allocation Text/Structured Logger for .NET with StringInterpolation and Source Generator, built on top of a Microsoft.Extensions.Logging.
C#
1,262
star
10

SimdLinq

Drop-in replacement of LINQ aggregation operations extremely faster with SIMD.
C#
775
star
11

csbindgen

Generate C# FFI from Rust for automatically brings native code and C native library to .NET and Unity.
Rust
688
star
12

ObservableCollections

High performance observable collections and synchronized views, for WPF, Blazor, Unity.
C#
559
star
13

ProcessX

Simplify call an external process with the async streams in C# 8.0.
C#
453
star
14

YetAnotherHttpHandler

YetAnotherHttpHandler brings the power of HTTP/2 (and gRPC) to Unity and .NET Standard.
C#
354
star
15

UnitGenerator

C# Source Generator to create value-object, inspired by units of measure.
C#
330
star
16

RuntimeUnitTestToolkit

CLI/GUI Frontend of Unity Test Runner to test on any platform.
C#
300
star
17

AlterNats

An alternative high performance NATS client for .NET.
C#
284
star
18

NativeMemoryArray

Utilized native-memory backed array for .NET and Unity - over the 2GB limitation and support the modern API(IBufferWriter, ReadOnlySequence, scatter/gather I/O, etc...).
C#
276
star
19

StructureOfArraysGenerator

Structure of arrays source generator to make CPU Cache and SIMD friendly data structure for high-performance code in .NET and Unity.
C#
262
star
20

MagicPhysX

.NET PhysX 5 binding to all platforms(win, osx, linux) for 3D engine, deep learning, dedicated server of gaming.
Rust
258
star
21

PrivateProxy

Source Generator and .NET 8 UnsafeAccessor based high-performance strongly-typed private accessor for unit testing and runtime.
C#
239
star
22

KcpTransport

KcpTransport is a Pure C# implementation of RUDP for high-performance real-time network communication
C#
237
star
23

LogicLooper

A library for building server application using loop-action programming model on .NET.
C#
237
star
24

DFrame

Distributed load testing framework for .NET and Unity.
C#
223
star
25

Utf8StreamReader

Utf8 based StreamReader for high performance text processing.
C#
208
star
26

LitJWT

Lightweight, Fast JWT(JSON Web Token) implementation for .NET.
C#
199
star
27

Claudia

Unofficial Anthropic Claude API client for .NET.
C#
162
star
28

CsprojModifier

CsprojModifier performs additional processing when Unity Editor generates the .csproj.
C#
154
star
29

Utf8StringInterpolation

Successor of ZString; UTF8 based zero allocation high-peformance String Interpolation and StringBuilder.
C#
153
star
30

ValueTaskSupplement

Append supplemental methods(WhenAny, WhenAll, Lazy) to ValueTask.
C#
135
star
31

Kokuban

Simplifies styling strings in the terminal for .NET application.
C#
123
star
32

SlnMerge

SlnMerge merges the solution files when generating solution file by Unity Editor.
C#
114
star
33

GrpcWebSocketBridge

Yet Another gRPC over HTTP/1 using WebSocket implementation, primarily targets .NET platform.
C#
76
star
34

WebSerializer

Convert Object into QueryString/FormUrlEncodedContent for C# HttpClient REST Request.
C#
65
star
35

RandomFixtureKit

Fill random/edge-case value to target type for unit testing, supports both .NET Standard and Unity.
C#
46
star
36

Actions

41
star
37

DocfxTemplate

Patchworked DocFX v2 template for Cysharp
JavaScript
7
star
38

Multicaster

A framework for transparently invoking multiple instances or clients.
C#
5
star
39

com.unity.ide.visualstudio-backport

Backport of com.unity.ide.visualstudio to before Unity 2019.4.21
C#
1
star