Git Product home page Git Product logo

fixedstrings's Introduction

FixedStrings ci NuGet

FixedStrings provides a zero allocation valuetype based fixed string implementation with the following size 8/16/32/64.

// Zero allocation!
FixedString16 str = $"HelloWorld {DateTime.Now.Year}";
// Prints "HelloWorld 2023"
Console.Out.WriteLine(str.AsSpan());

Features

  • Zero allocation via FixedString8, FixedString16, FixedString32 and FixedString64 structs.
  • Compatible with net7.0+

User Guide

Why FixedStrings?

Many modern applications are suffering from lots of allocations on the heap, and it is very frequent to see dozen of thousands of strings allocated on the managed heap. Having all these managed objects around is creating a lot more pressure on the GC, they can be more scattered in memory.

In many scenarios, you might be able to co-locate such strings closer to the class that are using them, but you might be able also to refine the memory requirement/usage for these strings.

For instance, on a 64 bit system, a single allocation of an empty managed string on the heap will take 24 bytes + 8 bytes for the reference to it. That's 32 bytes for an empty string! See details on sharplab.io.

With a fixed string, like FixedString8, you get 7 characters and it takes only 16 bytes or a FixedString16 would give similarly 15 characters while taking only 32 bytes!

As you can see in the benchmarks below, by avoiding an allocation to the heap, FixedStrings can be 2x as fast as creating them on the heap.

How does it work?

FixedStrings is relying on the C# 10 interpolated string handlers feature.

But unlike classical usage of interpolated string handlers, a FixedString is in fact itself an interpolation handler, using a fixed size buffer to store the string.

Fixed String Type Maximum Number of Chars Total Size
FixedString8 7 16 bytes
FixedString16 15 32 bytes
FixedString32 31 64 bytes
FixedString64 63 128 bytes

Each fixed string contains a short value for the length.

For example FixedString8 is declared like this:

[InterpolatedStringHandler]
public struct FixedString8 : IFixedString<FixedString8>
{
    private short _length;
    private short _c0;
    private short _c1;
    private short _c2;
    private short _c3;
    private short _c4;
    private short _c5;
    private short _c6;

    // ...
}

It is using a short for the internal representation of each characters to avoid marshalling issues - so that each character is passed as a plain short (UTF-16) value to the native side.

You can then copy around by value this string very easily and you can have a better control of the layout in memory.

Usage and restrictions

FixedStrings are not meant to replace all strings in your application. They are meant to be used for strings that are known to be short and that are used in a very hot path of your application.

  • If you try to add more characters than the size of the fixed string, it will be truncated. For practical reasons, It won't throw an exception!

  • FixedStrings support interpolation:

    FixedString8 str = $"Hello {name}";

    For performance reasons, supported types for values are: string and any types implementing ISpanFormattable (e.g int, float...etc.). A fixed string is itself ISpanFormattable and can be used as a value - and nested in string interpolations.

    Note that if a non string interpolated value cannot fit within the fixed string, it won't be emitted and the string will be truncated (in case of using a string). For example

    FixedString8 str = $"{"Hello"}{"World"}";

    will result in str containing "HelloWo" (7 characters). but the following interpolation:

    FixedString8 str = $"Hello{int.MaxValue}";

    will result in str containing "Hello", with the int value being discarded as it cannot fit within the fixed string.

  • Supporting alignment and format for interpolated values

    byte value = 10; 
    FixedString16 str = $"Test 0x{value:X2}";
  • FixedStrings support assigning from a regular string:

    FixedString8 str = "Hello";
  • You can get a ReadOnlySpan<char> directly from a FixedString:

    FixedString8 str = "Hello";
    ReadOnlySpan<char> span = str.AsSpan();
  • FixedStrings can be copied by value:

    FixedString8 str = "Hello";
    FixedString8 str2 = str;

    str2 will be a copy of str.

  • FixedStrings implement IFixedString<T> and can be used as a generic constraint:

    public int Foo<T>(T value) where T : IFixedString<T>
    {
        // ...
        return value.Length;
    }

Benchmarks

TestFixed is using a FixedString and TestDynamic is using a regular string.

  • For FixedString8, the performance gain is 2.5x faster than using a regular string.
  • For FixedString16, the performance gain is 2x faster than using a regular string.
  • For FixedString32 / FixedString64, the performance gain is 30% faster than using a regular string.
Method Runtime Mean Allocated
TestFixed8 .NET 7.0 13.70 ns -
TestDynamic8 .NET 7.0 31.33 ns 40 B
TestFixed8 .NET 8.0 10.05 ns -
TestDynamic8 .NET 8.0 26.47 ns 40 B
TestFixed16 .NET 7.0 17.56 ns -
TestDynamic16 .NET 7.0 32.52 ns 56 B
TestFixed16 .NET 8.0 14.25 ns -
TestDynamic16 .NET 8.0 27.80 ns 56 B
TestFixed32 .NET 7.0 38.27 ns -
TestDynamic32 .NET 7.0 49.70 ns 86 B
TestFixed32 .NET 8.0 30.12 ns -
TestDynamic32 .NET 8.0 38.15 ns 86 B
TestFixed64 .NET 7.0 61.37 ns -
TestDynamic64 .NET 7.0 80.15 ns 144 B
TestFixed64 .NET 8.0 43.96 ns -
TestDynamic64 .NET 8.0 59.32 ns 144 B

Building FixedStrings

In order to build FixedStrings, you need:

dotnet build -c Release src/FixedStrings.sln

License

This software is released under the BSD-2-Clause license.

Author

Alexandre Mutel aka xoofx.

fixedstrings's People

Contributors

xoofx avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.