Home

Awesome

Sep - Possibly the World's Fastest .NET CSV Parser

.NET C# Build Status Super-Linter codecov CodeQL Nuget Release downloads Size License Blog

Modern, minimal, fast, zero allocation, reading and writing of separated values (csv, tsv etc.). Cross-platform, trimmable and AOT/NativeAOT compatible. Featuring an opinionated API design and pragmatic implementation targetted at machine learning use cases.

⭐ Please star this project if you like it. ⭐

Example | Naming and Terminology | API | Limitations and Constraints | Comparison Benchmarks | Example Catalogue | RFC-4180 | FAQ | Public API Reference

Example

var text = """
           A;B;C;D;E;F
           Sep;🚀;1;1.2;0.1;0.5
           CSV;✅;2;2.2;0.2;1.5
           """;

using var reader = Sep.Reader().FromText(text);   // Infers separator 'Sep' from header
using var writer = reader.Spec.Writer().ToText(); // Writer defined from reader 'Spec'
                                                  // Use .FromFile(...)/ToFile(...) for files
var idx = reader.Header.IndexOf("B");
var nms = new[] { "E", "F" };

foreach (var readRow in reader)           // Read one row at a time
{
    var a = readRow["A"].Span;            // Column as ReadOnlySpan<char>
    var b = readRow[idx].ToString();      // Column to string (might be pooled)
    var c = readRow["C"].Parse<int>();    // Parse any T : ISpanParsable<T>
    var d = readRow["D"].Parse<float>();  // Parse float/double fast via csFastFloat
    var s = readRow[nms].Parse<double>(); // Parse multiple columns as Span<T>
                                          // - Sep handles array allocation and reuse
    foreach (ref var v in s) { v *= 10; }

    using var writeRow = writer.NewRow(); // Start new row. Row written on Dispose.
    writeRow["A"].Set(a);                 // Set by ReadOnlySpan<char>
    writeRow["B"].Set(b);                 // Set by string
    writeRow["C"].Set($"{c * 2}");        // Set via InterpolatedStringHandler, no allocs
    writeRow["D"].Format(d / 2);          // Format any T : ISpanFormattable
    writeRow[nms].Format(s);              // Format multiple columns directly
    // Columns are added on first access as ordered, header written when first row written
}

var expected = """
               A;B;C;D;E;F
               Sep;🚀;2;0.6;1;5
               CSV;✅;4;1.1;2;15
               
               """;                       // Empty line at end is for line ending,
                                          // which is always written.
Assert.AreEqual(expected, writer.ToString());

// Above example code is for demonstration purposes only.
// Short names and repeated constants are only for demonstration.

Naming and Terminology

Sep uses naming and terminology that is not based on RFC-4180, but is more tailored to usage in machine learning or similar. Additionally, Sep takes a pragmatic approach towards names by using short names and abbreviations where it makes sense and there should be no ambiguity given the context. That is, using Sep for Separator and Col for Column to keep code succinct.

TermDescription
SepShort for separator, also called delimiter. E.g. comma (,) is the separator for the separated values in a csv-file.
HeaderOptional first row defining names of columns.
RowA row is a collection of col(umn)s, which may span multiple lines. Also called record.
ColShort for column, also called field.
LineHorizontal set of characters until a line ending; \r\n, \r, \n.
Index0-based that is RowIndex will be 0 for first row (or the header if present).
Number1-based that is LineNumber will be 1 for the first line (as in notepad). Given a row may span multiple lines a row can have a From line number and a ToExcl line number matching the C# range indexing syntax [LineNumberFrom..LineNumberToExcl].

Application Programming Interface (API)

Besides being the succinct name of the library, Sep is both the main entry point to using the library and the container for a validated separator. That is, Sep is basically defined as:

public readonly record struct Sep(char Separator);

The separator char is validated upon construction and is guaranteed to be within a limited range and not being a char like " (quote) or similar. This can be seen in src/Sep/Sep.cs. The separator is constrained also for internal optimizations, so you cannot use any char as a separator.

⚠ Note that all types are within the namespace nietras.SeparatedValues and not Sep since it is problematic to have a type and a namespace with the same name.

To get started you can use Sep as the static entry point to building either a reader or writer. That is, for SepReader:

using var reader = Sep.Reader().FromFile("titanic.csv");

where .Reader() is a convenience method corresponding to:

using var reader = Sep.Auto.Reader().FromFile("titanic.csv");

where Sep? Auto => null; is a static property that returns null for a nullable Sep to signify that the separator should be inferred from the first row, which might be a header. If the first row does not contain any of the by default supported separators or there are no rows, the default separator will be used.

⚠ Note Sep uses ; as the default separator, since this is what was used in an internal proprietary library which Sep was built to replace. This is also to avoid issues with comma , being used as a decimal separator in some locales. Without having to resort to quoting.

If you want to specify the separator you can write:

using var reader = Sep.New(',').Reader().FromFile("titanic.csv");

or

var sep = new Sep(',');
using var reader = sep.Reader().FromFile("titanic.csv");

Similarly, for SepWriter:

using var writer = Sep.Writer().ToFile("titanic.csv");

or

using var writer = Sep.New(',').Writer().ToFile("titanic.csv");

where you have to specify a valid separator, since it cannot be inferred. To fascillitate easy flow of the separator and CultureInfo both SepReader and SepWriter expose a Spec property of type SepSpec that simply defines those two. This means you can write:

using var reader = Sep.Reader().FromFile("titanic.csv");
using var writer = reader.Spec.Writer().ToFile("titanic-survivors.csv");

where the writer then will use the separator inferred by the reader, for example.

API Pattern

In general, both reading and writing follow a similar pattern:

Sep/Spec => SepReaderOptions => SepReader => Row => Col(s) => Span/ToString/Parse
Sep/Spec => SepWriterOptions => SepWriter => Row => Col(s) => Set/Format

where each continuation flows fluently from the preceding type. For example, Reader() is an extension method to Sep or SepSpec that returns a SepReaderOptions. Similarly, Writer() is an extension method to Sep or SepSpec that returns a SepWriterOptions.

SepReaderOptions and SepWriterOptions are optionally configurable. That and the APIs for reader and writer is covered in the following sections.

For a complete example, see the example above or the ReadMeTest.cs.

⚠ Note that it is important to understand that Sep Row/Col/Cols are ref structs (please follow the ref struct link and understand how this limits the usage of those). This is due to these types being simple facades or indirections to the underlying reader or writer. That means you cannot use LINQ or create an array of all rows like reader.ToArray(). While for .NET9+ the reader is now IEnumerable<> since ref structs can now be used in interfaces that have where T: allows ref struct this still does not mean it is LINQ compatible. Hence, if you need store per row state or similar you need to parse or copy to different types instead. The same applies to Col/Cols which point to internal state that is also reused. This is to avoid repeated allocations for each row and get the best possible performance, while still defining a well structured and straightforward API that guides users to relevant functionality. See Why SepReader Was Not IEnumerable Until .NET 9 and Is Not LINQ Compatible for more.

⚠ For a full overview of public types and methods see Public API Reference.

SepReader API

SepReader API has the following structure (in pseudo-C# code):

using var reader = Sep.Reader(o => o).FromFile/FromText/From...;
var header = reader.Header;
var _ = header.IndexOf/IndicesOf/NamesStartingWith...;
foreach (var row in reader)
{
    var _ = row[colName/colNames].Span/ToString/Parse<T>...;
    var _ = row[colIndex/colIndices].Span/ToString/Parse<T>...;
}

That is, to use SepReader follow the points below:

  1. Optionally define Sep or use default automatically inferred separator.
  2. Specify reader with optional configuration of SepReaderOptions. For example, if a csv-file does not have a header this can be configured via:
    Sep.Reader(o => o with { HasHeader = false })
    
    For all options see SepReaderOptions.
  3. Specify source e.g. file, text (string), TextWriter, etc. via From extension methods.
  4. Optionally access the header. For example, to get all columns starting with GT_ use:
    var colNames = header.NamesStarting("GT_");
    var colIndices = header.IndicesOf(colNames);
    
  5. Enumerate rows. One row at a time.
  6. Access a column by name or index. Or access multiple columns with names and indices. Sep internally handles pooled allocation and reuse of arrays for multiple columns.
  7. Use Span to access the column directly as a ReadOnlySpan<char>. Or use ToString to convert to a string. Or use Parse<T> where T : ISpanParsable<T> to parse the column chars to a specific type.

SepReaderOptions

The following options are available:

/// <summary>
/// Specifies the separator used, if `null` then automatic detection 
/// is used based on first row in source.
/// </summary>
public Sep? Sep { get; init; } = null;
/// <summary>
/// Specifies initial internal `char` buffer length.
/// </summary>
/// <remarks>
/// The length will likely be rounded up to the nearest power of 2. A
/// smaller buffer may end up being used if the underlying source for <see
/// cref="System.IO.TextReader"/> is known to be smaller. Prefer to keep the
/// default length as that has been tuned for performance and cache sizes.
/// Avoid making this unnecessarily large as that will likely not improve
/// performance and may waste memory.
/// </remarks>
public int InitialBufferLength { get; init; } = SepDefaults.InitialBufferLength;
/// <summary>
/// Specifies the culture used for parsing. 
/// May be `null` for default culture.
/// </summary>
public CultureInfo? CultureInfo { get; init; } = SepDefaults.CultureInfo;
/// <summary>
/// Indicates whether the first row is a header row.
/// </summary>
public bool HasHeader { get; init; } = true;
/// <summary>
/// Specifies <see cref="IEqualityComparer{T}" /> to use 
/// for comparing header column names and looking up index.
/// </summary>
public IEqualityComparer<string> ColNameComparer { get; init; } = SepDefaults.ColNameComparer;
/// <summary>
/// Specifies the method factory used to convert a column span 
/// of `char`s to a `string`.
/// </summary>
public SepCreateToString CreateToString { get; init; } = SepToString.Direct;
/// <summary>
/// Disables using [csFastFloat](https://github.com/CarlVerret/csFastFloat)
/// for parsing `float` and `double`.
/// </summary>
public bool DisableFastFloat { get; init; } = false;
/// <summary>
/// Disables checking if column count is the same for all rows.
/// </summary>
public bool DisableColCountCheck { get; init; } = false;
/// <summary>
/// Disables detecting and parsing quotes.
/// </summary>
public bool DisableQuotesParsing { get; init; } = false;
/// <summary>
/// Unescape quotes on column access.
/// </summary>
/// <remarks>
/// When true, if a column starts with a quote then the two outermost quotes
/// are removed and every second inner quote is removed. Note that
/// unquote/unescape happens in-place, which means the <see
/// cref="SepReader.Row.Span" /> will be modified and contain "garbage"
/// state after unescaped cols before next col. This is for efficiency to
/// avoid allocating secondary memory for unescaped columns. Header
/// columns/names will also be unescaped.
/// Requires <see cref="DisableQuotesParsing"/> to be false.
/// </remarks>
public bool Unescape { get; init; } = false;
/// <summary>
/// Option for trimming spaces (` ` - ASCII 32) on column access.
/// </summary>
/// <remarks>
/// By default no trimming is done. See <see cref="SepTrim"/> for options.
/// Note that trimming may happen in-place e.g. if also unescaping, which
/// means the <see cref="SepReader.Row.Span" /> will be modified and contain
/// "garbage" state for trimmed/unescaped cols. This is for efficiency to
/// avoid allocating secondary memory for trimmed/unescaped columns. Header
/// columns/names will also be trimmed. Note that only the space ` ` (ASCII
/// 32) character is trimmed, not any whitespace character.
/// </remarks>
public SepTrim Trim { get; init; } = SepTrim.None;

Unescaping

While great care has been taken to ensure Sep unescaping of quotes is both correct and fast, there is always the question of how does one respond to invalid input.

The below table tries to summarize the behavior of Sep vs CsvHelper and Sylvan. Note that all do the same for valid input. There are differences for how invalid input is handled. For Sep the design choice has been based on not wanting to throw exceptions and to use a principle that is both reasonably fast and simple.

InputValidCsvHelperCsvHelper¹SylvanSep²
aTrueaaaa
""True
""""True""""
""""""True""""""""
"a"Trueaaaa
"a""a"Truea"aa"aa"aa"a
"a""a""a"Truea"a"aa"a"aa"a"aa"a"a
a""aFalseEXCEPTIONa""aa""aa""a
a"a"aFalseEXCEPTIONa"a"aa"a"aa"a"a
·""·FalseEXCEPTION·""··""··""·
·"a"·FalseEXCEPTION·"a"··"a"··"a"·
·""FalseEXCEPTION·""·""·""
·"a"FalseEXCEPTION·"a"·"a"·"a"
a"""aFalseEXCEPTIONa"""aa"""aa"""a
"a"a"a"FalseEXCEPTIONaa"a"a"a"aaa"a
""·FalseEXCEPTION·"·
"a"·FalseEXCEPTIONa"
"a"""aFalseEXCEPTIONaaEXCEPTIONa"a
"a"""a"FalseEXCEPTIONaa"a"a<NULL>a"a"
""a"FalseEXCEPTIONa""aa"
"a"a"FalseEXCEPTIONaa"a"aaa"
""a"a""FalseEXCEPTIONa"a"""a"a"a"a"
"""FalseEXCEPTION"
"""""False""EXCEPTION""

· (middle dot) is whitespace to make this visible

¹ CsvHelper with BadDataFound = null

² Sep with Unescape = true in SepReaderOptions

Trimming

Sep supports trimming by the SepTrim flags enum, which has two options as documented there. Below the result of both trimming and unescaping is shown in comparison to CsvHelper. Note unescaping is enabled for all results shown. It is possible to trim without unescaping too, of course.

As can be seen Sep supports a simple principle of trimming before and after unescaping with trimming before unescaping being important for unescaping if there is a starting quote after spaces.

InputCsvHelper TrimCsvHelper InsideQuotesCsvHelper All¹Sep OuterSep AfterUnescapeSep All²
aaaaaaa
·aa·aaaaa
aaaaa
·a·a·a·aaaa
·a·a·a·a·a·a·a·aa·aa·aa·a
"a"aaaaaa
"·a"·aaa·aaa
"a·"aaaa
"·a·"·a·aa·a·aa
"·a·a·"·a·a·a·aa·a·a·a·a·aa·a
·"a"·a·"a"·aa"a"a
·"·a"··a·"·a"·a·a"·a"a
·"a·"··"a·"·a"a·"a
·"·a·"··a··"·a·"·a·a·"·a·"a
·"·a·a·"··a·a··"·a·a·"·a·a·a·a·"·a·a·"a·a

· (middle dot) is whitespace to make this visible

¹ CsvHelper with TrimOptions.Trim | TrimOptions.InsideQuotes

² Sep with SepTrim.All = SepTrim.Outer | SepTrim.AfterUnescape in SepReaderOptions

SepReader Debuggability

Debuggability is an important part of any library and while this is still a work in progress for Sep, SepReader does have a unique feature when looking at it and it's row or cols in a debug context. Given the below example code:

var text = """
           Key;Value
           A;"1
           2
           3"
           B;"Apple
           Banana
           Orange
           Pear"
           """;
using var reader = Sep.Reader().FromText(text);
foreach (var row in reader)
{
    // Hover over reader, row or col when breaking here
    var col = row[1];
    if (Debugger.IsAttached && row.RowIndex == 2) { Debugger.Break(); }
    Debug.WriteLine(col.ToString());
}

and you are hovering over reader when the break is triggered then this will show something like:

String Length=55

That is, it will show information of the source for the reader, in this case a string of length 55.

SepReader.Row Debuggability

If you are hovering over row then this will show something like:

  2:[5..9] = "B;\"Apple\r\nBanana\r\nOrange\r\nPear\""

This has the format shown below.

<ROWINDEX>:[<LINENUMBERRANGE>] = "<ROW>"

Note how this shows line number range [FromIncl..ToExcl], as in C# range expression, so that one can easily find the row in question in notepad or similar. This means Sep has to track line endings inside quotes and is an example of a feature that makes Sep a bit slower but which is a price considered worth paying.

GitHub doesn't show line numbers in code blocks so consider copying the example text to notepad or similar to see the effect.

Additionally, if you expand the row in the debugger (e.g. via the small triangle) you will see each column of the row similar to below.

00:'Key'   = "B"
01:'Value' = "\"Apple\r\nBanana\r\nOrange\r\nPear\""
SepReader.Col Debuggability

If you hover over col you should see:

"\"Apple\r\nBanana\r\nOrange\r\nPear\""

Why SepReader Was Not IEnumerable Until .NET 9 and Is Not LINQ Compatible

As mentioned earlier Sep only allows enumeration and access to one row at a time and SepReader.Row is just a simple facade or indirection to the underlying reader. This is why it is defined as a ref struct. In fact, the following code:

using var reader = Sep.Reader().FromText(text);
foreach (var row in reader)
{ }

can also be rewritten as:

using var reader = Sep.Reader().FromText(text);
while (reader.MoveNext())
{
    var row = reader.Current;
}

where row is just a facade for exposing row specific functionality. That is, row is still basically the reader underneath. Hence, let's look at using LINQ with SepReader implementing IEnumerable<SepReader.Row> and the Row not being a ref struct. Then, you would be able to write something like below:

using var reader = Sep.Reader().FromText(text);
SepReader.Row[] rows = reader.ToArray();

Given Row is just a facade for the reader, this would be equivalent to writing:

using var reader = Sep.Reader().FromText(text);
SepReader[] rows = reader.ToArray();

which hopefully makes it clear why this is not a good thing. The array would effectively be the reader repeated several times. If this would have to be supported one would have to allocate memory for each row always, which would basically be no different than a ReadLine approach as benchmarked in Comparison Benchmarks.

This is perhaps also the reason why no other efficient .NET CSV parser (known to author) implements an API pattern like Sep, but instead let the reader define all functionality directly and hence only let's you access the current row and cols on that. This API, however, is in this authors opinion not ideal and can be a bit confusing, which is why Sep is designed like it is. The downside is the above caveat.

The main culprit above is that for example ToArray() would store a ref struct in a heap allocated array, the actual enumeration is not a problem and hence implementing IEnumerable<SepReader.Row> is not the problem as such. The problem was that prior to .NET 9 it was not possible to implement this interface with T being a ref struct, but with C# 13 allows ref struct and .NET 9 having annotated such interfaces it is now possible and you can assign SepReader to IEnumerable, but most if not all of LINQ will still not work as shown below.

var text = """
           Key;Value
           A;1.1
           B;2.2
           """;
using var reader = Sep.Reader().FromText(text);
IEnumerable<SepReader.Row> enumerable = reader;
// Currently, most LINQ methods do not work for ref types. See below.
//
// The type 'SepReader.Row' may not be a ref struct or a type parameter
// allowing ref structs in order to use it as parameter 'TSource' in the
// generic type or method 'Enumerable.Select<TSource,
// TResult>(IEnumerable<TSource>, Func<TSource, TResult>)'
//
// enumerable.Select(row => row["Key"].ToString()).ToArray();

Calling Select should in principle be possible if this was annotated with allows ref struct, but it isn't currently.

If you want to use LINQ or similar you have to first parse or transform the rows into some other type and enumerate it. This is easy to do and instead of counting lines you should focus on how such enumeration can be easily expressed using C# iterators (aka yield return). With local functions this can be done inside a method like:

var text = """
           Key;Value
           A;1.1
           B;2.2
           """;
var expected = new (string Key, double Value)[] {
    ("A", 1.1),
    ("B", 2.2),
};

using var reader = Sep.Reader().FromText(text);
var actual = Enumerate(reader).ToArray();

CollectionAssert.AreEqual(expected, actual);

static IEnumerable<(string Key, double Value)> Enumerate(SepReader reader)
{
    foreach (var row in reader)
    {
        yield return (row["Key"].ToString(), row["Value"].Parse<double>());
    }
}

Now if instead refactoring this to something LINQ-compatible by defining a common Enumerate or similar method it could be:

var text = """
           Key;Value
           A;1.1
           B;2.2
           """;
var expected = new (string Key, double Value)[] {
    ("A", 1.1),
    ("B", 2.2),
};

using var reader = Sep.Reader().FromText(text);
var actual = Enumerate(reader,
    row => (row["Key"].ToString(), row["Value"].Parse<double>()))
    .ToArray();

CollectionAssert.AreEqual(expected, actual);

static IEnumerable<T> Enumerate<T>(SepReader reader, SepReader.RowFunc<T> select)
{
    foreach (var row in reader)
    {
        yield return select(row);
    }
}

In fact, Sep provides such a convenience extension method. And, discounting the Enumerate method, this does have less boilerplate, but not really more effective lines of code. The issue here is that this tends to favor factoring code in a way that can become very inefficient quickly. Consider if one wanted to only enumerate rows matching a predicate on Key which meant only 1% of rows were to be enumerated e.g.:

var text = """
           Key;Value
           A;1.1
           B;2.2
           """;
var expected = new (string Key, double Value)[] {
    ("B", 2.2),
};

using var reader = Sep.Reader().FromText(text);
var actual = reader.Enumerate(
    row => (row["Key"].ToString(), row["Value"].Parse<double>()))
    .Where(kv => kv.Item1.StartsWith('B'))
    .ToArray();

CollectionAssert.AreEqual(expected, actual);

This means you are still parsing the double (which is magnitudes slower than getting just the key) for all rows. Imagine if this was an array of floating points or similar. Not only would you then be parsing a lot of values you would also be allocated 99x arrays that aren't used after filtering with Where.

Instead, you should focus on how to express the enumeration in a way that is both efficient and easy to read. For example, the above could be rewritten as:

var text = """
           Key;Value
           A;1.1
           B;2.2
           """;
var expected = new (string Key, double Value)[] {
    ("B", 2.2),
};

using var reader = Sep.Reader().FromText(text);
var actual = Enumerate(reader).ToArray();

CollectionAssert.AreEqual(expected, actual);

static IEnumerable<(string Key, double Value)> Enumerate(SepReader reader)
{
    foreach (var row in reader)
    {
        var keyCol = row["Key"];
        if (keyCol.Span.StartsWith("B"))
        {
            yield return (keyCol.ToString(), row["Value"].Parse<double>());
        }
    }
}

To accomodate this Sep provides an overload for Enumerate that is similar to:

static IEnumerable<T> Enumerate<T>(this SepReader reader, SepReader.RowTryFunc<T> trySelect)
{
    foreach (var row in reader)
    {
        if (trySelect(row, out var value))
        {
            yield return value;
        }
    }
}

With this the above custom Enumerate can be replaced with:

var text = """
           Key;Value
           A;1.1
           B;2.2
           """;
var expected = new (string Key, double Value)[] {
    ("B", 2.2),
};

using var reader = Sep.Reader().FromText(text);
var actual = reader.Enumerate((SepReader.Row row, out (string Key, double Value) kv) =>
{
    var keyCol = row["Key"];
    if (keyCol.Span.StartsWith("B"))
    {
        kv = (keyCol.ToString(), row["Value"].Parse<double>());
        return true;
    }
    kv = default;
    return false;
}).ToArray();

CollectionAssert.AreEqual(expected, actual);

Note how this is pretty much the same length as the previous custom Enumerate. Also worse due to how C# requires specifying types for out parameters which then requires all parameter types for the lambda to be specified. Hence, in this case the custom Enumerate does not take significantly longer to write and is a lot more efficient than using LINQ .Where (also avoids allocating a string for key for each row) and is easier to debug and perhaps even read. All examples above can be seen in ReadMeTest.cs.

There is a strong case for having an enumerate API though and that is for parallelized enumeration, which will be discussed next.

ParallelEnumerate and Enumerate

As discussed in the previous section Sep provides Enumerate convenience extension methods, that should be used carefully. Alongside these there are ParallelEnumerate extension methods that provide very efficient multi-threaded enumeration. See benchmarks for numbers and Public API Reference.

ParallelEnumerate is build on top of LINQ AsParallel().AsOrdered() and will return exactly the same as Enumerate but with enumeration parallelized. This will use more memory during execution and as many threads as possible via the .NET thread pool. When using ParallelEnumerate one should, therefore (as always), be certain the provided delegate does not refer to or change any mutable state.

ParallelEnumerate comes with a lot of overhead compared to single-threaded foreach or Enumerate and should be used carefully based on measuring any potential benefit. Sep goes a long way to make this very efficient by using pooled arrays and parsing multiple rows in batches, but if the source only has a few rows then any benefit is unlikely.

Due to ParallelEnumerate being based on batches of rows it is also important not to "abuse" it in-place of LINQ AsParallel. The idea is to use it for parsing rows, not for doing expensive per row operations like loading an image or similar. In that case, you are better off using AsParallel() after ParallelEnumerate or Enumerate similarly to:

using var reader = Sep.Reader().FromFile("very-long.csv");
var results = reader.ParallelEnumerate(ParseRow)
                    .AsParallel().AsOrdered()
                    .Select(LoadData) // Expensive load
                    .ToList();

As a rule of thumb if the time per row exceeds 1 millisecond consider moving the expensive work to after ParallelEnumerate/Enumerate,

SepWriter API

SepWriter API has the following structure (in pseudo-C# code):

using var writer = Sep.Writer(o => o).ToFile/ToText/To...;
foreach (var data in EnumerateData())
{
    using var row = writer.NewRow();
    var _ = row[colName/colNames].Set/Format<T>...;
    var _ = row[colIndex/colIndices].Set/Format<T>...;
}

That is, to use SepWriter follow the points below:

  1. Optionally define Sep or use default automatically inferred separator.
  2. Specify writer with optional configuration of SepWriterOptions. For all options see SepWriterOptions.
  3. Specify destination e.g. file, text (string via StringWriter), TextWriter, etc. via To extension methods.
  4. MISSING: SepWriter currently does not allow you to define the header up front. Instead, header is defined by the order in which column names are accessed/created when defining the row.
  5. Define new rows with NewRow. ⚠ Be sure to dispose any new rows before starting the next! For convenience Sep provides an overload for NewRow that takes a SepReader.Row and copies the columns from that row to the new row:
    using var reader = Sep.Reader().FromText(text);
    using var writer = reader.Spec.Writer().ToText();
    foreach (var readRow in reader)
    {   using var writeRow = writer.NewRow(readRow); }
    
  6. Create a column by selecting by name or index. Or multiple columns via indices and names. Sep internally handles pooled allocation and reuse of arrays for multiple columns.
  7. Use Set to set the column value either as a ReadOnlySpan<char>, string or via an interpolated string. Or use Format<T> where T : IFormattable to format T to the column value.
  8. Row is written when Dispose is called on the row.

    Note this is to allow a row to be defined flexibly with both column removal, moves and renames in the future. This is not yet supported.

SepWriterOptions

The following options are available:

/// <summary>
/// Specifies the separator used.
/// </summary>
public Sep Sep { get; init; }
/// <summary>
/// Specifies the culture used for parsing. 
/// May be `null` for default culture.
/// </summary>
public CultureInfo? CultureInfo { get; init; }
/// <summary>
/// Specifies whether to write a header row 
/// before data rows. Requires all columns 
/// to have a name. Otherwise, columns can be
/// added by indexing alone.
/// </summary>
public bool WriteHeader { get; init; } = true;

Limitations and Constraints

Sep is designed to be minimal and fast. As such, it has some limitations and constraints, since these are not needed for the initial intended usage:

Comparison Benchmarks

To investigate the performance of Sep it is compared to:

All benchmarks are run from/to memory either with:

This to avoid confounding factors from reading from or writing to disk.

When using StringReader/StringWriter each char counts as 2 bytes, when measuring throughput e.g. MB/s. When using StreamReader/StreamWriter content is UTF-8 encoded and each char typically counts as 1 byte, as content usually limited to 1 byte per char in UTF-8. Note that in .NET for TextReader and TextWriter data is converted to/from char, but for reading such conversion can often be just as fast as Memmove.

By default only StringReader/StringWriter results are shown, if a result is based on StreamReader/StreamWriter it will be called out. Usually, results for StreamReader/StreamWriter are in line with StringReader/StringWriter but with half the throughput due to 1 byte vs 2 bytes. For brevity they are not shown here.

For all benchmark results, Sep has been defined as the Baseline in BenchmarkDotNet. This means Ratio will be 1.00 for Sep. For the others Ratio will then show how many times faster Sep is than that. Or how many times more bytes are allocated in Alloc Ratio.

Disclaimer: Any comparison made is based on a number of preconditions and assumptions. Sep is a new library written from the ground up to use the latest and greatest features in .NET. CsvHelper has a long history and has to take into account backwards compatibility and still supporting older runtimes, so may not be able to easily utilize more recent features. Same goes for Sylvan. Additionally, Sep has a different feature set compared to the two. Performance is a feature, but not the only feature. Keep that in mind when evaluating results.

Runtime and Platforms

The following runtime is used for benchmarking:

NOTE: Garbage Collection DATAS mode is disabled since this severely impacts (e.g. 1.7x slower) performance for some benchmarks due to the bursty accumulated allocations. That is, GarbageCollectionAdaptationMode is set to 0.

The following platforms are used for benchmarking:

Reader Comparison Benchmarks

The following reader scenarios are benchmarked:

Details for each can be found in the following. However, for each of these 3 different scopes are benchmarked to better assertain the low-level performance of each library and approach and what parts of the parsing consume the most time:

Additionally, as Sep supports multi-threaded parsing via ParallelEnumerate benchmarks results with _MT in the method name are multi-threaded. These show Sep provides unparalleled performance compared to any other CSV parser.

NCsvPerf PackageAssets Reader Comparison Benchmarks

NCsvPerf from The fastest CSV parser in .NET is a benchmark which in Joel Verhagen own words was defined with:

My goal was to find the fastest low-level CSV parser. Essentially, all I wanted was a library that gave me a string[] for each line where each field in the line was an element in the array.

What is great about this work is it tests a whole of 35 different libraries and approaches to this. Providing a great overview of those and their performance on this specific scenario. Given Sylvan is the fastest of those it is used as the one to beat here, while CsvHelper is used to compare to the most commonly used library.

The source used for this benchmark PackageAssetsBench.cs is a PackageAssets.csv with NuGet package information in 25 columns with rows like:

75fcf875-017d-4579-bfd9-791d3e6767f0,2020-11-28T01:50:41.2449947+00:00,Akinzekeel.BlazorGrid,0.9.1-preview,2020-11-27T22:42:54.3100000+00:00,AvailableAssets,RuntimeAssemblies,,,net5.0,,,,,,lib/net5.0/BlazorGrid.dll,BlazorGrid.dll,.dll,lib,net5.0,.NETCoreApp,5.0.0.0,,,0.0.0.0
75fcf875-017d-4579-bfd9-791d3e6767f0,2020-11-28T01:50:41.2449947+00:00,Akinzekeel.BlazorGrid,0.9.1-preview,2020-11-27T22:42:54.3100000+00:00,AvailableAssets,CompileLibAssemblies,,,net5.0,,,,,,lib/net5.0/BlazorGrid.dll,BlazorGrid.dll,.dll,lib,net5.0,.NETCoreApp,5.0.0.0,,,0.0.0.0
75fcf875-017d-4579-bfd9-791d3e6767f0,2020-11-28T01:50:41.2449947+00:00,Akinzekeel.BlazorGrid,0.9.1-preview,2020-11-27T22:42:54.3100000+00:00,AvailableAssets,ResourceAssemblies,,,net5.0,,,,,,lib/net5.0/de/BlazorGrid.resources.dll,BlazorGrid.resources.dll,.dll,lib,net5.0,.NETCoreApp,5.0.0.0,,,0.0.0.0
75fcf875-017d-4579-bfd9-791d3e6767f0,2020-11-28T01:50:41.2449947+00:00,Akinzekeel.BlazorGrid,0.9.1-preview,2020-11-27T22:42:54.3100000+00:00,AvailableAssets,MSBuildFiles,,,any,,,,,,build/Microsoft.AspNetCore.StaticWebAssets.props,Microsoft.AspNetCore.StaticWebAssets.props,.props,build,any,Any,0.0.0.0,,,0.0.0.0
75fcf875-017d-4579-bfd9-791d3e6767f0,2020-11-28T01:50:41.2449947+00:00,Akinzekeel.BlazorGrid,0.9.1-preview,2020-11-27T22:42:54.3100000+00:00,AvailableAssets,MSBuildFiles,,,any,,,,,,build/Akinzekeel.BlazorGrid.props,Akinzekeel.BlazorGrid.props,.props,build,any,Any,0.0.0.0,,,0.0.0.0

For Scope = Asset the columns are parsed into a PackageAsset class, which consists of 25 properties of which 22 are strings. Each asset is accumulated into a List<PackageAsset>. Each column is accessed as a string regardless.

This means this benchmark is dominated by turning columns into strings for the decently fast parsers. Hence, the fastest libraries in this test employ string pooling. That is, basically a custom dictionary from ReadOnlySpan<char> to string, which avoids allocating a new string for repeated values. And as can be seen in the csv-file there are a lot of repeated values. Both Sylvan and CsvHelper do this in the benchmark. So does Sep and as with Sep this is an optional configuration that has to be explicitly enable. For Sep this means the reader is created with something like:

using var reader = Sep.Reader(o => o with
{
    HasHeader = false,
    CreateToString = SepToString.PoolPerCol(maximumStringLength: 128),
})
.From(CreateReader());

What is unique for Sep is that it allows defining a pool per column e.g. via SepToString.PoolPerCol(...). This is based on the fact that often each column has its own set of values or strings that may be repeated without any overlap to other columns. This also allows one to define per column specific handling of ToString behavior. Whether to pool or not. Or even to use a statically defined pool.

Sep supports unescaping via an option, see SepReaderOptions and Unescaping. Therefore, Sep has two methods being tested. The default Sep without unescaping and Sep_Unescape where unescaping is enabled. Note that only if there are quotes will there be any unescaping, but to support unescape one has to track extra state during parsing which means there is a slight cost no matter what, most notably for the Cols scope. Sep is still the fastest of all (by far in many cases).

PackageAssets Benchmark Results

The results below show Sep is the fastest .NET CSV Parser (for this benchmark on these platforms and machines 😀). While for pure parsing allocating only a fraction of the memory due to extensive use of pooling and the ArrayPool<T>.

This is in many aspects due to Sep having extremely optimized string pooling and optimized hashing of ReadOnlySpan<char>, and thus not really due the the csv-parsing itself, since that is not a big part of the time consumed. At least not for a decently fast csv-parser.

With ParallelEnumerate (MT) Sep is >2x faster than Sylvan and up to 9x faster than CsvHelper.

AMD.EPYC.7763 - PackageAssets Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row500003.582 ms1.00298120.571.61.03 KB1.00
Sep_UnescapeRow500003.568 ms1.00298151.271.41.03 KB1.00
Sylvan___Row500004.468 ms1.25296510.089.47.66 KB7.47
ReadLine_Row5000049.799 ms13.9129584.1996.088608.38 KB86,414.26
CsvHelperRow5000066.445 ms18.5529437.71328.923.3 KB22.72
Sep______Cols500004.848 ms1.00295999.497.01.2 KB1.00
Sep_UnescapeCols500005.710 ms1.18295093.7114.21.04 KB0.86
Sylvan___Cols500008.223 ms1.70293537.2164.57.68 KB6.41
ReadLine_Cols5000025.293 ms5.22291150.0505.988608.32 KB73,888.37
CsvHelperCols50000109.877 ms22.6629264.72197.5445.93 KB371.85
Sep______Asset5000030.823 ms1.0029943.6616.513802.34 KB1.00
Sep_MT___Asset5000023.560 ms0.76291234.6471.213852.34 KB1.00
Sylvan___Asset5000047.591 ms1.5429611.2951.813961.85 KB1.01
ReadLine_Asset50000116.425 ms3.7829249.82328.5102133.09 KB7.40
CsvHelperAsset50000120.019 ms3.8929242.32400.413970.29 KB1.01
Sep______Asset1000000797.462 ms1.00581729.7797.5266669.05 KB1.00
Sep_MT___Asset1000000507.024 ms0.645811147.6507.0275457.14 KB1.03
Sylvan___Asset1000000991.891 ms1.25581586.6991.9266826.74 KB1.00
ReadLine_Asset10000003,259.026 ms4.09581178.53259.02038846.35 KB7.65
CsvHelperAsset10000002,527.438 ms3.17581230.22527.4266850.81 KB1.00
AMD.Ryzen.7.PRO.7840U.w.Radeon.780M - PackageAssets Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row500004.200 ms1.00296948.284.01.18 KB1.00
Sep_UnescapeRow500004.236 ms1.01296888.684.71.33 KB1.13
Sylvan___Row500004.491 ms1.07296497.989.87.66 KB6.49
ReadLine_Row5000021.321 ms5.08291368.7426.488608.28 KB75,049.53
CsvHelperRow5000062.781 ms14.9529464.81255.620.2 KB17.11
Sep______Cols500005.852 ms1.00294986.3117.01.19 KB1.00
Sep_UnescapeCols500006.573 ms1.12294439.6131.51.19 KB1.00
Sylvan___Cols500008.553 ms1.46293411.8171.17.67 KB6.44
ReadLine_Cols5000022.541 ms3.85291294.6450.888608.29 KB74,372.86
CsvHelperCols50000108.328 ms18.5129269.42166.6445.78 KB374.16
Sep______Asset5000053.003 ms1.0029550.61060.113803.34 KB1.00
Sep_MT___Asset5000038.829 ms0.7429751.5776.613913.62 KB1.01
Sylvan___Asset5000070.050 ms1.3329416.61401.013962.4 KB1.01
ReadLine_Asset50000233.476 ms4.4229125.04669.5102134.79 KB7.40
CsvHelperAsset50000133.896 ms2.5429217.92677.913972.19 KB1.01
Sep______Asset1000000993.034 ms1.00583587.9993.0266670.95 KB1.00
Sep_MT___Asset1000000504.125 ms0.515831158.0504.1268509.69 KB1.01
Sylvan___Asset10000001,206.663 ms1.22583483.81206.7266825.98 KB1.00
ReadLine_Asset10000003,256.930 ms3.28583179.23256.92038848 KB7.65
CsvHelperAsset10000002,657.874 ms2.68583219.62657.9266843.54 KB1.00
AMD.Ryzen.9.5950X - PackageAssets Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row500002.188 ms1.002913339.943.81.02 KB1.00
Sep_UnescapeRow500002.214 ms1.012913181.444.31.02 KB1.00
Sylvan___Row500002.825 ms1.292910328.756.57.66 KB7.53
ReadLine_Row5000011.707 ms5.35292492.7234.188608.25 KB87,161.24
CsvHelperRow5000043.779 ms20.0129666.6875.620.04 KB19.71
Sep______Cols500003.210 ms1.00299091.864.21.02 KB1.00
Sep_UnescapeCols500003.856 ms1.20297567.477.11.02 KB1.00
Sylvan___Cols500005.072 ms1.58295753.7101.47.66 KB7.51
ReadLine_Cols5000013.080 ms4.08292230.9261.688608.25 KB86,827.61
CsvHelperCols5000071.032 ms22.1329410.81420.6445.86 KB436.90
Sep______Asset5000032.075 ms1.0029909.8641.513802.45 KB1.00
Sep_MT___Asset5000019.243 ms0.60291516.5384.913993.52 KB1.01
Sylvan___Asset5000034.429 ms1.0729847.6688.613963.52 KB1.01
ReadLine_Asset5000095.729 ms2.9929304.81914.6102133.9 KB7.40
CsvHelperAsset5000082.784 ms2.5829352.51655.713970.93 KB1.01
Sep______Asset1000000627.827 ms1.00583929.8627.8266680.78 KB1.00
Sep_MT___Asset1000000254.075 ms0.405832297.7254.1267692.5 KB1.00
Sylvan___Asset1000000736.667 ms1.17583792.5736.7266825.22 KB1.00
ReadLine_Asset10000001,585.514 ms2.53583368.21585.52038834.79 KB7.65
CsvHelperAsset10000001,661.220 ms2.65583351.41661.2266833.3 KB1.00
Apple.M1.(Virtual) - PackageAssets Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row500003.761 ms1.00297732.975.2988 B1.00
Sep_UnescapeRow500004.202 ms1.12296921.584.01033 B1.05
Sylvan___Row5000019.616 ms5.22291482.7392.36958 B7.04
ReadLine_Row5000017.984 ms4.78291617.3359.790734887 B91,836.93
CsvHelperRow5000042.806 ms11.3829679.5856.120764 B21.02
Sep______Cols500005.242 ms1.00295548.3104.8995 B1.00
Sep_UnescapeCols500005.306 ms1.01295481.3106.1994 B1.00
Sylvan___Cols5000022.184 ms4.23291311.1443.76958 B6.99
ReadLine_Cols5000019.444 ms3.71291495.9388.990734891 B91,190.85
CsvHelperCols5000066.750 ms12.7329435.71335.0456636 B458.93
Sep______Asset5000032.905 ms1.0029883.9658.114134044 B1.00
Sep_MT___Asset5000021.284 ms0.65291366.5425.714236153 B1.01
Sylvan___Asset5000052.459 ms1.6029554.41049.214296308 B1.01
ReadLine_Asset5000090.785 ms2.7729320.41815.7104586002 B7.40
CsvHelperAsset5000079.577 ms2.4329365.51591.514305850 B1.01
Sep______Asset1000000586.057 ms1.00581992.9586.1273070336 B1.00
Sep_MT___Asset1000000450.524 ms0.775811291.6450.5283959880 B1.04
Sylvan___Asset10000001,054.994 ms1.80581551.51055.0273242248 B1.00
ReadLine_Asset10000001,834.688 ms3.13581317.21834.72087769376 B7.65
CsvHelperAsset10000001,561.048 ms2.66581372.71561.0273242536 B1.00
PackageAssets Benchmark Results (SERVER GC)

The package assets benchmark (Scope Asset) has a very high base load in the form of the accumulated instances of PackageAsset and since Sep is so fast the GC becomes a significant bottleneck for the benchmark, especially for multi-threaded parsing. Switching to SERVER GC can, therefore, provide significant speedup as can be seen below.

With ParallelEnumerate and server GC Sep is >4x faster than Sylvan and up to 18x faster than CsvHelper. Breaking 4 GB/s parsing speed on package assets on 5950X.

AMD.EPYC.7763 - PackageAssets Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000032.39 ms1.0029898.1647.713.48 MB1.00
Sep_MT___Asset5000014.89 ms0.46291953.6297.813.53 MB1.00
Sylvan___Asset5000041.94 ms1.3029693.5838.913.63 MB1.01
ReadLine_Asset5000037.66 ms1.1629772.3753.399.74 MB7.40
CsvHelperAsset50000121.64 ms3.7629239.12432.913.64 MB1.01
Sep______Asset1000000620.61 ms1.00581937.6620.6260.41 MB1.00
Sep_MT___Asset1000000287.75 ms0.465812022.2287.7269.46 MB1.03
Sylvan___Asset1000000828.44 ms1.33581702.4828.4260.57 MB1.00
ReadLine_Asset10000001,307.41 ms2.11581445.11307.41991.05 MB7.65
CsvHelperAsset10000002,355.53 ms3.80581247.02355.5260.58 MB1.00
AMD.Ryzen.7.PRO.7840U.w.Radeon.780M - PackageAssets Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000032.87 ms1.0029887.7657.413.48 MB1.00
Sep_MT___Asset5000012.08 ms0.37292415.5241.613.57 MB1.01
Sylvan___Asset5000044.10 ms1.3429661.7881.913.63 MB1.01
ReadLine_Asset5000046.91 ms1.4329622.1938.299.74 MB7.40
CsvHelperAsset50000117.89 ms3.5929247.52357.813.64 MB1.01
Sep______Asset1000000712.78 ms1.00583819.0712.8260.41 MB1.00
Sep_MT___Asset1000000280.21 ms0.395832083.3280.2261.5 MB1.00
Sylvan___Asset1000000911.34 ms1.28583640.6911.3260.57 MB1.00
ReadLine_Asset10000001,080.48 ms1.52583540.31080.51991.05 MB7.65
CsvHelperAsset10000002,393.86 ms3.37583243.92393.9260.58 MB1.00
AMD.Ryzen.9.5950X - PackageAssets Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000020.739 ms1.00291407.1414.813.48 MB1.00
Sep_MT___Asset500006.042 ms0.29294829.6120.813.64 MB1.01
Sylvan___Asset5000027.858 ms1.34291047.5557.213.63 MB1.01
ReadLine_Asset5000032.844 ms1.5829888.5656.999.74 MB7.40
CsvHelperAsset5000076.303 ms3.6829382.41526.113.64 MB1.01
Sep______Asset1000000435.624 ms1.005831340.1435.6260.41 MB1.00
Sep_MT___Asset1000000116.180 ms0.275835024.8116.2261.3 MB1.00
Sylvan___Asset1000000558.898 ms1.285831044.5558.9260.57 MB1.00
ReadLine_Asset1000000573.815 ms1.325831017.4573.81991.05 MB7.65
CsvHelperAsset10000001,504.212 ms3.45583388.11504.2260.58 MB1.00
Apple.M1.(Virtual) - PackageAssets Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000026.67 ms1.00291090.7533.313.48 MB1.00
Sep_MT___Asset5000020.88 ms0.78291393.1417.613.66 MB1.01
Sylvan___Asset5000051.56 ms1.9329564.21031.113.63 MB1.01
ReadLine_Asset5000044.37 ms1.6729655.5887.599.74 MB7.40
CsvHelperAsset5000080.94 ms3.0429359.41618.713.64 MB1.01
Sep______Asset1000000547.04 ms1.005811063.7547.0260.41 MB1.00
Sep_MT___Asset1000000227.53 ms0.425812557.4227.5266.03 MB1.02
Sylvan___Asset10000001,058.09 ms1.93581549.91058.1260.57 MB1.00
ReadLine_Asset10000001,105.75 ms2.02581526.21105.81991.05 MB7.65
CsvHelperAsset10000001,588.28 ms2.90581366.41588.3260.58 MB1.00
PackageAssets with Quotes Benchmark Results

NCsvPerf does not examine performance in the face of quotes in the csv. This is relevant since some libraries like Sylvan will revert to a slower (not SIMD vectorized) parsing code path if it encounters quotes. Sep was designed to always use SIMD vectorization no matter what.

Since there are two extra chars to handle per column, it does have a significant impact on performance, no matter what though. This is expected when looking at the numbers. For each row of 25 columns, there are 24 separators (here ,) and one set of line endings (here \r\n). That's 26 characters. Adding quotes around each of the 25 columns will add 50 characters or almost triple the total to 76.

AMD.EPYC.7763 - PackageAssets with Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row5000010.54 ms1.00333159.0210.71.06 KB1.00
Sep_UnescapeRow5000010.80 ms1.02333083.0215.91.06 KB1.00
Sylvan___Row5000026.19 ms2.49331270.9523.77.74 KB7.30
ReadLine_Row5000028.51 ms2.71331167.2570.3108778.83 KB102,568.62
CsvHelperRow5000076.92 ms7.3033432.71538.320.28 KB19.12
Sep______Cols5000011.63 ms1.00332860.6232.71.07 KB1.00
Sep_UnescapeCols5000013.58 ms1.17332450.1271.71.08 KB1.01
Sylvan___Cols5000030.23 ms2.60331100.8604.77.76 KB7.25
ReadLine_Cols5000029.64 ms2.55331122.7592.9108778.84 KB101,540.13
CsvHelperCols50000105.52 ms9.0733315.42110.3445.86 KB416.19
Sep______Asset5000038.31 ms1.0033868.8766.113802.34 KB1.00
Sep_MT___Asset5000026.27 ms0.69331266.9525.413864.9 KB1.00
Sylvan___Asset5000062.31 ms1.6333534.11246.313964.99 KB1.01
ReadLine_Asset50000138.98 ms3.6333239.52779.6122303.89 KB8.86
CsvHelperAsset50000117.01 ms3.0533284.42340.313970.29 KB1.01
Sep______Asset1000000958.41 ms1.00665694.7958.4266669.05 KB1.00
Sep_MT___Asset1000000609.74 ms0.646651091.9609.7269433.56 KB1.01
Sylvan___Asset10000001,452.68 ms1.52665458.31452.7266827.02 KB1.00
ReadLine_Asset10000003,888.60 ms4.06665171.23888.62442326.16 KB9.16
CsvHelperAsset10000002,539.78 ms2.65665262.12539.8266834.94 KB1.00
AMD.Ryzen.7.PRO.7840U.w.Radeon.780M - PackageAssets with Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row5000010.531 ms1.00333169.5210.61.21 KB1.00
Sep_UnescapeRow500009.910 ms0.94333368.2198.21.21 KB1.00
Sylvan___Row5000026.180 ms2.49331274.9523.67.72 KB6.38
ReadLine_Row5000024.019 ms2.28331389.6480.4108778.78 KB89,902.72
CsvHelperRow5000071.228 ms6.7633468.61424.620.2 KB16.70
Sep______Cols5000011.933 ms1.00332797.1238.71.22 KB1.00
Sep_UnescapeCols5000013.486 ms1.13332474.9269.71.22 KB1.00
Sylvan___Cols5000029.535 ms2.48331130.1590.77.73 KB6.35
ReadLine_Cols5000026.438 ms2.22331262.5528.8108778.78 KB89,397.65
CsvHelperCols50000104.426 ms8.7533319.62088.5445.78 KB366.36
Sep______Asset5000057.695 ms1.0033578.51153.913803.3 KB1.00
Sep_MT___Asset5000047.415 ms0.8233703.9948.313941.84 KB1.01
Sylvan___Asset5000092.123 ms1.6033362.31842.513962.42 KB1.01
ReadLine_Asset50000196.126 ms3.4033170.23922.5122305.15 KB8.86
CsvHelperAsset50000127.767 ms2.2233261.22555.313972.13 KB1.01
Sep______Asset10000001,129.007 ms1.00667591.41129.0266670.93 KB1.00
Sep_MT___Asset1000000674.504 ms0.60667989.9674.5268208.37 KB1.01
Sylvan___Asset10000001,656.453 ms1.47667403.11656.5266825.34 KB1.00
ReadLine_Asset10000004,269.727 ms3.78667156.44269.72442331.02 KB9.16
CsvHelperAsset10000002,581.438 ms2.29667258.72581.4266834.02 KB1.00
AMD.Ryzen.9.5950X - PackageAssets with Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row500007.077 ms1.00334716.4141.51.04 KB1.00
Sep_UnescapeRow500006.916 ms0.98334826.4138.31.04 KB1.00
Sylvan___Row5000016.794 ms2.37331987.5335.97.69 KB7.42
ReadLine_Row5000014.068 ms1.99332372.5281.4108778.74 KB104,886.47
CsvHelperRow5000052.336 ms7.4033637.71046.720.01 KB19.29
Sep______Cols500007.709 ms1.00334329.4154.21.03 KB1.00
Sep_UnescapeCols500008.991 ms1.17333712.1179.81.04 KB1.01
Sylvan___Cols5000019.529 ms2.53331709.2390.67.7 KB7.47
ReadLine_Cols5000015.205 ms1.97332195.1304.1108778.76 KB105,482.43
CsvHelperCols5000070.755 ms9.1833471.71415.1448.87 KB435.27
Sep______Asset5000037.129 ms1.0033899.0742.613803.03 KB1.00
Sep_MT___Asset5000021.253 ms0.57331570.5425.113981.42 KB1.01
Sylvan___Asset5000048.990 ms1.3233681.3979.813962.13 KB1.01
ReadLine_Asset50000118.684 ms3.2033281.22373.7122305.02 KB8.86
CsvHelperAsset5000083.758 ms2.2633398.51675.213970.38 KB1.01
Sep______Asset1000000707.538 ms1.00667943.7707.5266668.99 KB1.00
Sep_MT___Asset1000000349.710 ms0.496671909.3349.7268243.91 KB1.01
Sylvan___Asset10000001,022.358 ms1.44667653.11022.4266825.07 KB1.00
ReadLine_Asset10000002,210.209 ms3.12667302.12210.22442320.25 KB9.16
CsvHelperAsset10000001,709.222 ms2.42667390.61709.2266833.3 KB1.00
Apple.M1.(Virtual) - PackageAssets with Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row5000010.03 ms1.00333318.2200.61018 B1.00
Sep_UnescapeRow5000010.06 ms1.00333309.9201.11093 B1.07
Sylvan___Row5000021.10 ms2.10331577.5422.06958 B6.83
ReadLine_Row5000020.90 ms2.08331592.2418.1111389487 B109,419.93
CsvHelperRow5000046.54 ms4.6433715.1930.820764 B20.40
Sep______Cols5000011.19 ms1.00332973.6223.81026 B1.00
Sep_UnescapeCols5000012.09 ms1.08332752.0241.91127 B1.10
Sylvan___Cols5000024.91 ms2.23331336.1498.26958 B6.78
ReadLine_Cols5000021.52 ms1.92331546.3430.5111389493 B108,566.76
CsvHelperCols5000071.19 ms6.3633467.51423.8459732 B448.08
Sep______Asset5000034.77 ms1.0033957.1695.414134032 B1.00
Sep_MT___Asset5000026.38 ms0.76331261.6527.614200790 B1.00
Sylvan___Asset5000055.33 ms1.5933601.51106.614297352 B1.01
ReadLine_Asset50000129.30 ms3.7233257.42586.0125240862 B8.86
CsvHelperAsset5000084.84 ms2.4433392.31696.814305848 B1.01
Sep______Asset1000000812.54 ms1.00665819.4812.5273070232 B1.00
Sep_MT___Asset1000000517.67 ms0.646651286.2517.7280315208 B1.03
Sylvan___Asset10000001,208.02 ms1.49665551.21208.0273235192 B1.00
ReadLine_Asset10000002,483.07 ms3.06665268.12483.12500937776 B9.16
CsvHelperAsset10000001,769.26 ms2.18665376.31769.3273246256 B1.00
PackageAssets with Quotes Benchmark Results (SERVER GC)

Here again are benchmark results with server garbage collection, which provides significant speedup over workstation garbage collection.

AMD.EPYC.7763 - PackageAssets with Quotes Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000040.61 ms1.0033819.6812.113.48 MB1.00
Sep_MT___Asset5000020.94 ms0.52331589.1418.913.54 MB1.00
Sylvan___Asset5000065.44 ms1.6133508.61308.713.63 MB1.01
ReadLine_Asset5000041.99 ms1.0333792.6839.8119.44 MB8.86
CsvHelperAsset50000120.35 ms2.9633276.62406.913.64 MB1.01
Sep______Asset1000000775.60 ms1.00665858.4775.6260.41 MB1.00
Sep_MT___Asset1000000386.10 ms0.506651724.4386.1263.07 MB1.01
Sylvan___Asset10000001,276.57 ms1.65665521.61276.6260.57 MB1.00
ReadLine_Asset10000001,451.32 ms1.87665458.81451.32385.07 MB9.16
CsvHelperAsset10000002,331.93 ms3.01665285.52331.9260.58 MB1.00
AMD.Ryzen.7.PRO.7840U.w.Radeon.780M - PackageAssets with Quotes Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000039.42 ms1.0033846.8788.313.48 MB1.00
Sep_MT___Asset5000023.61 ms0.60331413.5472.313.59 MB1.01
Sylvan___Asset5000065.68 ms1.6733508.21313.513.63 MB1.01
ReadLine_Asset5000083.86 ms2.1333398.01677.2119.44 MB8.86
CsvHelperAsset50000112.64 ms2.8633296.32252.913.64 MB1.01
Sep______Asset1000000853.65 ms1.00667782.2853.6260.41 MB1.00
Sep_MT___Asset1000000383.82 ms0.456671739.6383.8261.86 MB1.01
Sylvan___Asset10000001,351.84 ms1.58667493.91351.8260.57 MB1.00
ReadLine_Asset10000001,173.87 ms1.38667568.81173.92385.07 MB9.16
CsvHelperAsset10000002,305.37 ms2.70667289.62305.4260.58 MB1.00
AMD.Ryzen.9.5950X - PackageAssets with Quotes Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000025.49 ms1.00331309.5509.813.48 MB1.00
Sep_MT___Asset5000011.02 ms0.43333027.8220.513.64 MB1.01
Sylvan___Asset5000042.03 ms1.6533794.1840.613.63 MB1.01
ReadLine_Asset5000038.66 ms1.5233863.3773.2119.44 MB8.86
CsvHelperAsset5000078.18 ms3.0733426.91563.713.64 MB1.01
Sep______Asset1000000519.82 ms1.006671284.5519.8260.41 MB1.00
Sep_MT___Asset1000000210.37 ms0.406673173.9210.4261.48 MB1.00
Sylvan___Asset1000000870.28 ms1.67667767.2870.3260.57 MB1.00
ReadLine_Asset1000000630.49 ms1.216671059.0630.52385.07 MB9.16
CsvHelperAsset10000001,559.67 ms3.00667428.11559.7260.58 MB1.00
Apple.M1.(Virtual) - PackageAssets with Quotes Benchmark Results (SERVER GC) (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Asset5000032.36 ms1.00331028.5647.213.48 MB1.00
Sep_MT___Asset5000014.74 ms0.46332258.4294.713.59 MB1.01
Sylvan___Asset5000052.76 ms1.6333630.81055.313.63 MB1.01
ReadLine_Asset5000040.49 ms1.2533821.9809.9119.44 MB8.86
CsvHelperAsset5000084.67 ms2.6233393.11693.313.64 MB1.01
Sep______Asset1000000664.17 ms1.006651002.5664.2260.41 MB1.00
Sep_MT___Asset1000000353.26 ms0.536651884.7353.3267.27 MB1.03
Sylvan___Asset10000001,082.34 ms1.63665615.11082.3260.57 MB1.00
ReadLine_Asset10000001,249.34 ms1.88665532.91249.32385.07 MB9.16
CsvHelperAsset10000001,598.74 ms2.41665416.51598.7260.58 MB1.00
PackageAssets with Spaces and Quotes Benchmark Results

Similar to the benchmark related to quotes here spaces and quotes " are added to relevant columns to benchmark impact of trimming and unescape on low level column access. That is, basically " is prepended and appended to each column. This will test the assumed most common case and fast path part of trimming and unescaping in Sep. Sep is about 10x faster than CsvHelper for this. Sylvan does not appear to have support automatic trimming and is, therefore, not included.

AMD.EPYC.7763 - PackageAssets with Spaces and Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep_Cols5000012.91 ms1.00413228.2258.21.08 KB1.00
Sep_TrimCols5000018.40 ms1.43412265.4367.91.11 KB1.03
Sep_TrimUnescapeCols5000018.79 ms1.46412218.5375.71.11 KB1.03
Sep_TrimUnescapeTrimCols5000020.42 ms1.58412041.2408.31.11 KB1.03
CsvHelper_TrimUnescapeCols50000144.51 ms11.1941288.42890.1451.72 KB419.75
CsvHelper_TrimUnescapeTrimCols50000144.37 ms11.1841288.72887.5446.2 KB414.61
AMD.Ryzen.7.PRO.7840U.w.Radeon.780M - PackageAssets with Spaces and Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep_Cols5000013.26 ms1.00413149.0265.31.22 KB1.00
Sep_TrimCols5000018.75 ms1.41412228.2374.91.24 KB1.02
Sep_TrimUnescapeCols5000019.82 ms1.49412107.2396.51.25 KB1.02
Sep_TrimUnescapeTrimCols5000022.54 ms1.70411853.0450.81.27 KB1.04
CsvHelper_TrimUnescapeCols50000129.86 ms9.7941321.72597.2454.53 KB372.95
CsvHelper_TrimUnescapeTrimCols50000127.98 ms9.6541326.42559.5445.86 KB365.83
AMD.Ryzen.9.5950X - PackageAssets with Spaces and Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep_Cols500008.599 ms1.00414857.5172.01.04 KB1.00
Sep_TrimCols5000012.402 ms1.44413368.0248.01.05 KB1.01
Sep_TrimUnescapeCols5000013.201 ms1.54413164.1264.01.06 KB1.02
Sep_TrimUnescapeTrimCols5000014.568 ms1.69412867.3291.41.07 KB1.02
CsvHelper_TrimUnescapeCols5000096.272 ms11.2041433.91925.4451.52 KB432.51
CsvHelper_TrimUnescapeTrimCols5000095.183 ms11.0741438.81903.7445.86 KB427.09
Apple.M1.(Virtual) - PackageAssets with Spaces and Quotes Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep_Cols5000012.70 ms1.00413282.0254.01.01 KB1.00
Sep_TrimCols5000015.72 ms1.24412650.5314.51.19 KB1.17
Sep_TrimUnescapeCols5000016.28 ms1.28412559.8325.61.03 KB1.02
Sep_TrimUnescapeTrimCols5000021.21 ms1.67411964.6424.31.37 KB1.35
CsvHelper_TrimUnescapeCols5000088.96 ms7.0141468.51779.2451.6 KB445.94
CsvHelper_TrimUnescapeTrimCols5000086.97 ms6.8541479.21739.4445.93 KB440.34

Floats Reader Comparison Benchmarks

The FloatsReaderBench.cs benchmark demonstrates what Sep is built for. Namely parsing 32-bit floating points or features as in machine learning. Here a simple CSV-file is randomly generated with N ground truth values, N predicted result values and nothing else (note this was changed from version 0.3.0, prior to that there were some extra leading columns). N = 20 here. For example:

GT_Feature0;GT_Feature1;GT_Feature2;GT_Feature3;GT_Feature4;GT_Feature5;GT_Feature6;GT_Feature7;GT_Feature8;GT_Feature9;GT_Feature10;GT_Feature11;GT_Feature12;GT_Feature13;GT_Feature14;GT_Feature15;GT_Feature16;GT_Feature17;GT_Feature18;GT_Feature19;RE_Feature0;RE_Feature1;RE_Feature2;RE_Feature3;RE_Feature4;RE_Feature5;RE_Feature6;RE_Feature7;RE_Feature8;RE_Feature9;RE_Feature10;RE_Feature11;RE_Feature12;RE_Feature13;RE_Feature14;RE_Feature15;RE_Feature16;RE_Feature17;RE_Feature18;RE_Feature19
0.52276427;0.16843422;0.26259267;0.7244084;0.51292276;0.17365117;0.76125056;0.23458846;0.2573214;0.50560355;0.3202332;0.3809696;0.26024464;0.5174511;0.035318818;0.8141374;0.57719684;0.3974705;0.15219308;0.09011261;0.70515215;0.81618196;0.5399706;0.044147138;0.7111546;0.14776127;0.90621275;0.6925897;0.5164137;0.18637845;0.041509967;0.30819967;0.5831603;0.8210651;0.003954861;0.535722;0.8051845;0.7483589;0.3845737;0.14911908
0.6264564;0.11517637;0.24996082;0.77242833;0.2896067;0.6481459;0.14364648;0.044498358;0.6045593;0.51591337;0.050794687;0.42036617;0.7065823;0.6284636;0.21844554;0.013253775;0.36516154;0.2674384;0.06866083;0.71817476;0.07094294;0.46409357;0.012033525;0.7978093;0.43917948;0.5134962;0.4995968;0.008952909;0.82883793;0.012896823;0.0030740085;0.063773096;0.6541431;0.034539033;0.9135142;0.92897075;0.46119377;0.37533295;0.61660606;0.044443816
0.7922863;0.5323656;0.400699;0.29737252;0.9072584;0.58673894;0.73510516;0.019412167;0.88168067;0.9576787;0.33283427;0.7107;0.1623628;0.10314285;0.4521515;0.33324885;0.7761104;0.14854911;0.13469358;0.21566042;0.59166247;0.5128394;0.98702157;0.766223;0.67204326;0.7149494;0.2894748;0.55206;0.9898286;0.65083236;0.02421702;0.34540752;0.92906284;0.027142895;0.21974725;0.26544374;0.03848049;0.2161237;0.59233844;0.42221397
0.10609442;0.32130885;0.32383907;0.7511514;0.8258279;0.00904226;0.0420841;0.84049565;0.8958947;0.23807365;0.92621964;0.8452882;0.2794469;0.545344;0.63447595;0.62532926;0.19230893;0.29726416;0.18304513;0.029583583;0.23084833;0.93346167;0.98742676;0.78163713;0.13521992;0.8833956;0.18670778;0.29476836;0.5599867;0.5562107;0.7124796;0.121927656;0.5981778;0.39144602;0.88092715;0.4449142;0.34820423;0.96379805;0.46364686;0.54301775

For Scope=Floats the benchmark will parse the features as two spans of floats; one for ground truth values and one for predicted result values. Then calculates the mean squared error (MSE) of those as an example. For Sep this code is succinct and still incredibly efficient:

using var reader = Sep.Reader().From(Reader.CreateReader());

var groundTruthColNames = reader.Header.NamesStartingWith("GT_");
var resultColNames = groundTruthColNames.Select(n =>
    n.Replace("GT_", "RE_", StringComparison.Ordinal))
    .ToArray();

var sum = 0.0;
var count = 0;
foreach (var row in reader)
{
    var gts = row[groundTruthColNames].Parse<float>();
    var res = row[resultColNames].Parse<float>();

    sum += MeanSquaredError(gts, res);
    ++count;
}
return sum / count;

Note how one can access and parse multiple columns easily while there are no repeated allocations for the parsed floating points. Sep internally handles a pool of arrays for handling multiple columns and returns spans for them.

The benchmark is based on an assumption of accessing columns by name per row. Ideally, one would look up the indices of the columns by name before enumerating rows, but this is a repeated nuisance to have to handle and Sep was built to avoid this. Hence, the comparison is based on looking up by name for each, even if this ends up adding a bit more code in the benchmark for other approaches.

As can be seen below, the actual low level parsing of the separated values is a tiny part of the total runtime for Sep for which the runtime is dominated by parsing the floating points. Since Sep uses csFastFloat for an integrated fast floating point parser, it is >2x faster than Sylvan for example. If using Sylvan one may consider using csFastFloat if that is an option. With the multi-threaded (MT) ParallelEnumerate implementation Sep is up to 23x faster than Sylvan.

CsvHelper suffers from the fact that one can only access the column as a string so this has to be allocated for each column (ReadLine by definition always allocates a string per column). Still CsvHelper is significantly slower than the naive ReadLine approach. With Sep being >4x faster than CsvHelper and up to 35x times faster when using ParallelEnumerate.

Note that ParallelEnumerate provides significant speedup over single-threaded parsing even though the source is only about 20 MB. This underlines how efficient ParallelEnumerate is, but bear in mind that this is for the case of repeated micro-benchmark runs.

It is a testament to how good the .NET and the .NET GC is that the ReadLine is pretty good compared to CsvHelper regardless of allocating a lot of strings.

AMD.EPYC.7763 - FloatsReader Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row250002.913 ms1.00206958.2116.51.26 KB1.00
Sylvan___Row250003.511 ms1.21205774.0140.410.71 KB8.51
ReadLine_Row2500019.754 ms6.78201026.2790.273489.68 KB58,426.57
CsvHelperRow2500038.285 ms13.1420529.51531.420.06 KB15.95
Sep______Cols250003.876 ms1.00205230.0155.01.26 KB1.00
Sylvan___Cols250005.891 ms1.52203441.4235.610.72 KB8.51
ReadLine_Cols2500021.160 ms5.4620958.0846.473489.68 KB58,335.99
CsvHelperCols2500040.117 ms10.3520505.31604.721340.29 KB16,939.89
Sep______Floats2500031.349 ms1.0020646.71254.08.08 KB1.00
Sep_MT___Floats2500012.954 ms0.41201565.0518.167.81 KB8.40
Sylvan___Floats2500090.425 ms2.8820224.23617.018.96 KB2.35
ReadLine_Floats25000112.571 ms3.5920180.14502.973493.98 KB9,101.20
CsvHelperFloats25000160.313 ms5.1120126.56412.522062.29 KB2,732.11
AMD.Ryzen.7.PRO.7840U.w.Radeon.780M - FloatsReader Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row250003.386 ms1.00206000.5135.51.41 KB1.00
Sylvan___Row250003.782 ms1.12205372.1151.310.71 KB7.58
ReadLine_Row2500015.608 ms4.61201301.9624.373489.65 KB52,006.50
CsvHelperRow2500039.717 ms11.7320511.61588.720.03 KB14.17
Sep______Cols250004.509 ms1.00204506.2180.41.42 KB1.00
Sylvan___Cols250006.001 ms1.33203386.0240.010.71 KB7.56
ReadLine_Cols2500019.123 ms4.24201062.6764.973489.66 KB51,898.90
CsvHelperCols2500042.640 ms9.4620476.51705.621340.25 KB15,070.63
Sep______Floats2500030.981 ms1.0020655.91239.28.2 KB1.00
Sep_MT___Floats250008.686 ms0.28202339.4347.4115.48 KB14.08
Sylvan___Floats2500085.393 ms2.7620238.03415.718.88 KB2.30
ReadLine_Floats25000104.946 ms3.3920193.64197.873493.12 KB8,960.23
CsvHelperFloats25000156.745 ms5.0620129.66269.822062.08 KB2,689.79
AMD.Ryzen.9.5950X - FloatsReader Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row250001.909 ms1.002010643.376.41.25 KB1.00
Sylvan___Row250002.244 ms1.18209054.389.810.7 KB8.56
ReadLine_Row250009.875 ms5.17202057.8395.073489.63 KB58,791.71
CsvHelperRow2500024.433 ms12.8020831.6977.320 KB16.00
Sep______Cols250002.615 ms1.00207771.6104.61.25 KB1.00
Sylvan___Cols250003.744 ms1.43205427.2149.810.71 KB8.54
ReadLine_Cols2500010.169 ms3.89201998.1406.873489.63 KB58,654.23
CsvHelperCols2500026.080 ms9.9720779.11043.221340.22 KB17,032.26
Sep______Floats2500019.885 ms1.00201021.8795.47.99 KB1.00
Sep_MT___Floats250003.527 ms0.18205761.0141.1180.36 KB22.59
Sylvan___Floats2500052.686 ms2.6520385.72107.518.88 KB2.36
ReadLine_Floats2500066.897 ms3.3620303.72675.973493.12 KB9,203.49
CsvHelperFloats2500097.448 ms4.9020208.53897.922061.7 KB2,762.77
Apple.M1.(Virtual) - FloatsReader Benchmark Results (Sep 0.6.0.0, Sylvan 1.3.9.0, CsvHelper 33.0.1.24)
MethodScopeRowsMeanRatioMBMB/sns/rowAllocatedAlloc Ratio
Sep______Row250003.887 ms1.00205215.5155.51.2 KB1.00
Sylvan___Row2500017.956 ms4.62201129.0718.210.62 KB8.87
ReadLine_Row2500014.074 ms3.62201440.4563.073489.65 KB61,381.24
CsvHelperRow2500027.741 ms7.1420730.81109.620.28 KB16.94
Sep______Cols250004.726 ms1.00204289.0189.11.2 KB1.00
Sylvan___Cols2500020.241 ms4.28201001.5809.610.62 KB8.84
ReadLine_Cols2500014.976 ms3.17201353.6599.073489.65 KB61,181.63
CsvHelperCols2500029.842 ms6.3120679.31193.721340.5 KB17,766.40
Sep______Floats2500024.511 ms1.0020827.1980.48.34 KB1.00
Sep_MT___Floats250009.422 ms0.38202151.5376.979.89 KB9.58
Sylvan___Floats2500069.902 ms2.8520290.02796.118.57 KB2.23
ReadLine_Floats2500079.015 ms3.2220256.63160.673493.2 KB8,816.43
CsvHelperFloats25000104.811 ms4.2820193.44192.422063.34 KB2,646.77

Writer Comparison Benchmarks

Writer benchmarks are still pending, but Sep is unlikely to be the fastest here since it is explicitly designed to make writing more convenient and flexible. Still efficient, but not necessarily fastest. That is, Sep does not require writing header up front and hence having to keep header column order and row values column order the same. This means Sep does not write columns directly upon definition but defers this until a new row has been fully defined and then is ended.

Example Catalogue

The following examples are available in ReadMeTest.cs.

Example - Copy Rows

var text = """
           A;B;C;D;E;F
           Sep;🚀;1;1.2;0.1;0.5
           CSV;✅;2;2.2;0.2;1.5
           
           """; // Empty line at end is for line ending

using var reader = Sep.Reader().FromText(text);
using var writer = reader.Spec.Writer().ToText();
foreach (var readRow in reader)
{
    using var writeRow = writer.NewRow(readRow);
}
Assert.AreEqual(text, writer.ToString());

Example - Skip Empty Rows

var text = """
           A
           1
           2

           3


           4
           
           """; // Empty line at end is for line ending
var expected = new[] { 1, 2, 3, 4 };

// Disable col count check to allow empty rows
using var reader = Sep.Reader(o => o with { DisableColCountCheck = true }).FromText(text);
var actual = new List<int>();
foreach (var row in reader)
{
    // Skip empty row
    if (row.Span.Length == 0) { continue; }

    actual.Add(row["A"].Parse<int>());
}
CollectionAssert.AreEqual(expected, actual);

Example - Use Extension Method Enumerate within async/await Context

Since SepReader.Row is a ref struct as covered above, one has to avoid referencing it directly in async context. This can be done in a number of ways, but one way is to use Enumerate extension method to parse/extract data from row like shown below.

var text = """
           C
           1
           2
           """;

using var reader = Sep.Reader().FromText(text);
var squaredSum = 0;
// Use Enumerate to avoid referencing SepReader.Row in async context
foreach (var value in reader.Enumerate(row => row["C"].Parse<int>()))
{
    squaredSum += await Task.Run(() => value * value);
}
Assert.AreEqual(5, squaredSum);

Example - Use Local Function within async/await Context

Another way to avoid referencing SepReader.Row directly in async context is to use custom iterator via yield return to parse/extract data from row like shown below.

var text = """
           C
           1
           2
           """;

using var reader = Sep.Reader().FromText(text);
var squaredSum = 0;
// Use custom local function Enumerate to avoid referencing
// SepReader.Row in async context
foreach (var value in Enumerate(reader))
{
    squaredSum += await Task.Run(() => value * value);
}
Assert.AreEqual(5, squaredSum);

static IEnumerable<int> Enumerate(SepReader reader)
{
    foreach (var r in reader) { yield return r["C"].Parse<int>(); }
}

RFC-4180

While the RFC-4180 requires \r\n (CR,LF) as line ending, the well-known line endings (\r\n, \n and \r) are supported similar to .NET. Environment.NewLine is used when writing. Quoting is supported by simply matching pairs of quotes, no matter what.

Note that some libraries will claim conformance but the RFC is, perhaps naturally, quite strict e.g. only comma is supported as separator/delimiter. Sep defaults to using ; as separator if writing, while auto-detecting supported separators when reading. This is decidedly non-conforming.

The RFC defines the following condensed ABNF grammar:

file = [header CRLF] record *(CRLF record) [CRLF]
header = name *(COMMA name)
record = field *(COMMA field)
name = field
field = (escaped / non-escaped)
escaped = DQUOTE *(TEXTDATA / COMMA / CR / LF / 2DQUOTE) DQUOTE
non-escaped = *TEXTDATA
COMMA = %x2C
CR = %x0D ;as per section 6.1 of RFC 2234 [2]
DQUOTE =  %x22 ;as per section 6.1 of RFC 2234 [2]
LF = %x0A ;as per section 6.1 of RFC 2234 [2]
CRLF = CR LF ;as per section 6.1 of RFC 2234 [2]
TEXTDATA =  %x20-21 / %x23-2B / %x2D-7E

Note how TEXTDATA is restricted too, yet many will allow any character incl. emojis or similar (which Sep supports), but is not in conformance with the RFC.

Quotes inside an escaped field e.g. "fie""ld" are only allowed to be double quotes. Sep currently allows any pairs of quotes and quoting doesn't need to be at start of or end of field (col or column in Sep terminology).

All in all Sep takes a pretty pragmatic approach here as the primary use case is not exchanging data on the internet, but for use in machine learning pipelines or similar.

Frequently Asked Questions (FAQ)

Ask questions on GitHub and this section will be expanded. :)

SepReader FAQ

SepWriter FAQ

Links

Public API Reference

[assembly: System.CLSCompliant(false)]
[assembly: System.Reflection.AssemblyMetadata("IsTrimmable", "True")]
[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/nietras/Sep/")]
[assembly: System.Resources.NeutralResourcesLanguage("en")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Sep.Benchmarks")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Sep.ComparisonBenchmarks")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Sep.Test")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Sep.XyzTest")]
[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v9.0", FrameworkDisplayName=".NET 9.0")]
namespace nietras.SeparatedValues
{
    public readonly struct Sep : System.IEquatable<nietras.SeparatedValues.Sep>
    {
        public Sep() { }
        public Sep(char separator) { }
        public char Separator { get; init; }
        public static nietras.SeparatedValues.Sep? Auto { get; }
        public static nietras.SeparatedValues.Sep Default { get; }
        public static nietras.SeparatedValues.Sep New(char separator) { }
        public static nietras.SeparatedValues.SepReaderOptions Reader() { }
        public static nietras.SeparatedValues.SepReaderOptions Reader(System.Func<nietras.SeparatedValues.SepReaderOptions, nietras.SeparatedValues.SepReaderOptions> configure) { }
        public static nietras.SeparatedValues.SepWriterOptions Writer() { }
        public static nietras.SeparatedValues.SepWriterOptions Writer(System.Func<nietras.SeparatedValues.SepWriterOptions, nietras.SeparatedValues.SepWriterOptions> configure) { }
    }
    public delegate nietras.SeparatedValues.SepToString SepCreateToString(nietras.SeparatedValues.SepReaderHeader? maybeHeader, int colCount);
    public static class SepDefaults
    {
        public static System.StringComparer ColNameComparer { get; }
        public static System.Globalization.CultureInfo CultureInfo { get; }
        public static char Separator { get; }
    }
    [System.Diagnostics.DebuggerDisplay("{DebuggerDisplay,nq}")]
    public sealed class SepReader : nietras.SeparatedValues.SepReaderState, System.Collections.Generic.IEnumerable<nietras.SeparatedValues.SepReader.Row>, System.Collections.Generic.IEnumerator<nietras.SeparatedValues.SepReader.Row>, System.Collections.IEnumerable, System.Collections.IEnumerator, System.IDisposable
    {
        public nietras.SeparatedValues.SepReader.Row Current { get; }
        public bool HasHeader { get; }
        public bool HasRows { get; }
        public nietras.SeparatedValues.SepReaderHeader Header { get; }
        public bool IsEmpty { get; }
        public nietras.SeparatedValues.SepSpec Spec { get; }
        public nietras.SeparatedValues.SepReader GetEnumerator() { }
        public bool MoveNext() { }
        public string ToString(int index) { }
        [System.Diagnostics.DebuggerDisplay("{DebuggerDisplay}")]
        [System.Obsolete("Types with embedded references are not supported in this version of your compiler" +
            ".", true)]
        [System.Runtime.CompilerServices.CompilerFeatureRequired("RefStructs")]
        [System.Runtime.CompilerServices.IsByRefLike]
        public readonly struct Col
        {
            public System.ReadOnlySpan<char> Span { get; }
            public T Parse<T>()
                where T : System.ISpanParsable<T> { }
            public override string ToString() { }
            public T? TryParse<T>()
                where T :  struct, System.ISpanParsable<T> { }
            public bool TryParse<T>(out T value)
                where T : System.ISpanParsable<T> { }
        }
        [System.Obsolete("Types with embedded references are not supported in this version of your compiler" +
            ".", true)]
        [System.Runtime.CompilerServices.CompilerFeatureRequired("RefStructs")]
        [System.Runtime.CompilerServices.IsByRefLike]
        public readonly struct Cols
        {
            public int Count { get; }
            public nietras.SeparatedValues.SepReader.Col this[int index] { get; }
            public System.Span<T> Parse<T>()
                where T : System.ISpanParsable<T> { }
            public void Parse<T>(System.Span<T> span)
                where T : System.ISpanParsable<T> { }
            public T[] ParseToArray<T>()
                where T : System.ISpanParsable<T> { }
            public System.Span<T> Select<T>(method selector) { }
            public System.Span<T> Select<T>(nietras.SeparatedValues.SepReader.ColFunc<T> selector) { }
            public System.Span<string> ToStrings() { }
            public string[] ToStringsArray() { }
            public System.Span<T?> TryParse<T>()
                where T :  struct, System.ISpanParsable<T> { }
            public void TryParse<T>(System.Span<T?> span)
                where T :  struct, System.ISpanParsable<T> { }
        }
        [System.Diagnostics.DebuggerDisplay("{DebuggerDisplayPrefix,nq}{Span}")]
        [System.Diagnostics.DebuggerTypeProxy(typeof(nietras.SeparatedValues.SepReader.Row.DebugView))]
        [System.Obsolete("Types with embedded references are not supported in this version of your compiler" +
            ".", true)]
        [System.Runtime.CompilerServices.CompilerFeatureRequired("RefStructs")]
        [System.Runtime.CompilerServices.IsByRefLike]
        public readonly struct Row
        {
            public int ColCount { get; }
            public nietras.SeparatedValues.SepReader.Col this[int index] { get; }
            public nietras.SeparatedValues.SepReader.Col this[System.Index index] { get; }
            public nietras.SeparatedValues.SepReader.Col this[string colName] { get; }
            public nietras.SeparatedValues.SepReader.Cols this[System.Range range] { get; }
            public nietras.SeparatedValues.SepReader.Cols this[System.ReadOnlySpan<int> indices] { get; }
            public nietras.SeparatedValues.SepReader.Cols this[System.Collections.Generic.IReadOnlyList<int> indices] { get; }
            public nietras.SeparatedValues.SepReader.Cols this[int[] indices] { get; }
            public nietras.SeparatedValues.SepReader.Cols this[System.ReadOnlySpan<string> colNames] { get; }
            public nietras.SeparatedValues.SepReader.Cols this[System.Collections.Generic.IReadOnlyList<string> colNames] { get; }
            public nietras.SeparatedValues.SepReader.Cols this[string[] colNames] { get; }
            public int LineNumberFrom { get; }
            public int LineNumberToExcl { get; }
            public int RowIndex { get; }
            public System.ReadOnlySpan<char> Span { get; }
            public System.Func<int, string> UnsafeToStringDelegate { get; }
            public override string ToString() { }
        }
        public delegate void ColAction(nietras.SeparatedValues.SepReader.Col col);
        public delegate T ColFunc<T>(nietras.SeparatedValues.SepReader.Col col);
        public delegate void ColsAction(nietras.SeparatedValues.SepReader.Cols col);
        public delegate void RowAction(nietras.SeparatedValues.SepReader.Row row);
        public delegate T RowFunc<T>(nietras.SeparatedValues.SepReader.Row row);
        public delegate bool RowTryFunc<T>(nietras.SeparatedValues.SepReader.Row row, out T value);
    }
    public static class SepReaderExtensions
    {
        public static System.Collections.Generic.IEnumerable<T> Enumerate<T>(this nietras.SeparatedValues.SepReader reader, nietras.SeparatedValues.SepReader.RowFunc<T> select) { }
        public static System.Collections.Generic.IEnumerable<T> Enumerate<T>(this nietras.SeparatedValues.SepReader reader, nietras.SeparatedValues.SepReader.RowTryFunc<T> trySelect) { }
        public static nietras.SeparatedValues.SepReader From(in this nietras.SeparatedValues.SepReaderOptions options, byte[] buffer) { }
        public static nietras.SeparatedValues.SepReader From(in this nietras.SeparatedValues.SepReaderOptions options, System.IO.Stream stream) { }
        public static nietras.SeparatedValues.SepReader From(in this nietras.SeparatedValues.SepReaderOptions options, System.IO.TextReader reader) { }
        public static nietras.SeparatedValues.SepReader From(in this nietras.SeparatedValues.SepReaderOptions options, string name, System.Func<string, System.IO.Stream> nameToStream) { }
        public static nietras.SeparatedValues.SepReader From(in this nietras.SeparatedValues.SepReaderOptions options, string name, System.Func<string, System.IO.TextReader> nameToReader) { }
        public static nietras.SeparatedValues.SepReader FromFile(in this nietras.SeparatedValues.SepReaderOptions options, string filePath) { }
        public static nietras.SeparatedValues.SepReader FromText(in this nietras.SeparatedValues.SepReaderOptions options, string text) { }
        public static System.Collections.Generic.IEnumerable<T> ParallelEnumerate<T>(this nietras.SeparatedValues.SepReader reader, nietras.SeparatedValues.SepReader.RowFunc<T> select) { }
        public static System.Collections.Generic.IEnumerable<T> ParallelEnumerate<T>(this nietras.SeparatedValues.SepReader reader, nietras.SeparatedValues.SepReader.RowTryFunc<T> trySelect) { }
        public static System.Collections.Generic.IEnumerable<T> ParallelEnumerate<T>(this nietras.SeparatedValues.SepReader reader, nietras.SeparatedValues.SepReader.RowFunc<T> select, int degreeOfParallism) { }
        public static System.Collections.Generic.IEnumerable<T> ParallelEnumerate<T>(this nietras.SeparatedValues.SepReader reader, nietras.SeparatedValues.SepReader.RowTryFunc<T> trySelect, int degreeOfParallism) { }
        public static nietras.SeparatedValues.SepReaderOptions Reader(this nietras.SeparatedValues.Sep sep) { }
        public static nietras.SeparatedValues.SepReaderOptions Reader(this nietras.SeparatedValues.Sep? sep) { }
        public static nietras.SeparatedValues.SepReaderOptions Reader(this nietras.SeparatedValues.SepSpec spec) { }
        public static nietras.SeparatedValues.SepReaderOptions Reader(this nietras.SeparatedValues.Sep sep, System.Func<nietras.SeparatedValues.SepReaderOptions, nietras.SeparatedValues.SepReaderOptions> configure) { }
        public static nietras.SeparatedValues.SepReaderOptions Reader(this nietras.SeparatedValues.Sep? sep, System.Func<nietras.SeparatedValues.SepReaderOptions, nietras.SeparatedValues.SepReaderOptions> configure) { }
        public static nietras.SeparatedValues.SepReaderOptions Reader(this nietras.SeparatedValues.SepSpec spec, System.Func<nietras.SeparatedValues.SepReaderOptions, nietras.SeparatedValues.SepReaderOptions> configure) { }
    }
    public sealed class SepReaderHeader
    {
        public System.Collections.Generic.IReadOnlyList<string> ColNames { get; }
        public bool IsEmpty { get; }
        public static nietras.SeparatedValues.SepReaderHeader Empty { get; }
        public int IndexOf(System.ReadOnlySpan<char> colName) { }
        public int IndexOf(string colName) { }
        public int[] IndicesOf(System.Collections.Generic.IReadOnlyList<string> colNames) { }
        public int[] IndicesOf([System.Runtime.CompilerServices.ParamCollection] [System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan<string> colNames) { }
        public int[] IndicesOf(params string[] colNames) { }
        public void IndicesOf(System.ReadOnlySpan<string> colNames, System.Span<int> colIndices) { }
        public System.Collections.Generic.IReadOnlyList<string> NamesStartingWith(string prefix, System.StringComparison comparison = 4) { }
        public override string ToString() { }
        public bool TryIndexOf(System.ReadOnlySpan<char> colName, out int colIndex) { }
        public bool TryIndexOf(string colName, out int colIndex) { }
    }
    public readonly struct SepReaderOptions : System.IEquatable<nietras.SeparatedValues.SepReaderOptions>
    {
        public SepReaderOptions() { }
        public SepReaderOptions(nietras.SeparatedValues.Sep? sep) { }
        public System.Collections.Generic.IEqualityComparer<string> ColNameComparer { get; init; }
        public nietras.SeparatedValues.SepCreateToString CreateToString { get; init; }
        public System.Globalization.CultureInfo? CultureInfo { get; init; }
        public bool DisableColCountCheck { get; init; }
        public bool DisableFastFloat { get; init; }
        public bool DisableQuotesParsing { get; init; }
        public bool HasHeader { get; init; }
        public int InitialBufferLength { get; init; }
        public nietras.SeparatedValues.Sep? Sep { get; init; }
        public nietras.SeparatedValues.SepTrim Trim { get; init; }
        public bool Unescape { get; init; }
    }
    public class SepReaderState : System.IDisposable
    {
        public void Dispose() { }
    }
    public static class SepReaderWriterExtensions
    {
        public static void CopyTo(this nietras.SeparatedValues.SepReader.Row readerRow, nietras.SeparatedValues.SepWriter.Row writerRow) { }
        public static nietras.SeparatedValues.SepWriter.Row NewRow(this nietras.SeparatedValues.SepWriter writer, nietras.SeparatedValues.SepReader.Row rowToCopy) { }
    }
    public readonly struct SepSpec : System.IEquatable<nietras.SeparatedValues.SepSpec>
    {
        public SepSpec() { }
        public SepSpec(nietras.SeparatedValues.Sep sep, System.Globalization.CultureInfo? cultureInfo) { }
        public System.Globalization.CultureInfo? CultureInfo { get; init; }
        public nietras.SeparatedValues.Sep Sep { get; init; }
    }
    public abstract class SepToString : System.IDisposable
    {
        protected SepToString() { }
        public virtual bool IsThreadSafe { get; }
        public static nietras.SeparatedValues.SepCreateToString Direct { get; }
        public void Dispose() { }
        protected virtual void Dispose(bool disposing) { }
        public abstract string ToString(System.ReadOnlySpan<char> colSpan, int colIndex);
        public static nietras.SeparatedValues.SepCreateToString OnePool(int maximumStringLength = 32, int initialCapacity = 64, int maximumCapacity = 4096) { }
        public static nietras.SeparatedValues.SepCreateToString PoolPerCol(int maximumStringLength = 32, int initialCapacity = 64, int maximumCapacity = 4096) { }
        public static nietras.SeparatedValues.SepCreateToString PoolPerColThreadSafe(int maximumStringLength = 32, int initialCapacity = 64, int maximumCapacity = 4096) { }
        public static nietras.SeparatedValues.SepCreateToString PoolPerColThreadSafeFixedCapacity(int maximumStringLength = 32, int capacity = 2048) { }
    }
    [System.Flags]
    public enum SepTrim : byte
    {
        None = 0,
        Outer = 1,
        AfterUnescape = 2,
        All = 3,
    }
    public sealed class SepWriter : System.IDisposable
    {
        public nietras.SeparatedValues.SepWriterHeader Header { get; }
        public nietras.SeparatedValues.SepSpec Spec { get; }
        public void Dispose() { }
        public void Flush() { }
        public nietras.SeparatedValues.SepWriter.Row NewRow() { }
        public override string ToString() { }
        [System.Obsolete("Types with embedded references are not supported in this version of your compiler" +
            ".", true)]
        [System.Runtime.CompilerServices.CompilerFeatureRequired("RefStructs")]
        [System.Runtime.CompilerServices.IsByRefLike]
        public struct Row : System.IDisposable
        {
            public nietras.SeparatedValues.SepWriter.Col this[int colIndex] { get; }
            public nietras.SeparatedValues.SepWriter.Col this[string colName] { get; }
            public nietras.SeparatedValues.SepWriter.Cols this[System.ReadOnlySpan<int> indices] { get; }
            public nietras.SeparatedValues.SepWriter.Cols this[System.ReadOnlySpan<string> colNames] { get; }
            public nietras.SeparatedValues.SepWriter.Cols this[System.Collections.Generic.IReadOnlyList<string> colNames] { get; }
            public nietras.SeparatedValues.SepWriter.Cols this[string[] colNames] { get; }
            public void Dispose() { }
        }
        [System.Obsolete("Types with embedded references are not supported in this version of your compiler" +
            ".", true)]
        [System.Runtime.CompilerServices.CompilerFeatureRequired("RefStructs")]
        [System.Runtime.CompilerServices.IsByRefLike]
        public readonly struct Col
        {
            public void Format<T>(T value)
                where T : System.ISpanFormattable { }
            public void Set(System.ReadOnlySpan<char> span) { }
            public void Set([System.Runtime.CompilerServices.InterpolatedStringHandlerArgument("")] ref nietras.SeparatedValues.SepWriter.Col.FormatInterpolatedStringHandler handler) { }
            public void Set(System.IFormatProvider? provider, [System.Runtime.CompilerServices.InterpolatedStringHandlerArgument(new string?[]?[] {
                    "",
                    "provider"})] ref nietras.SeparatedValues.SepWriter.Col.FormatInterpolatedStringHandler handler) { }
            [System.Runtime.CompilerServices.InterpolatedStringHandler]
            public readonly struct FormatInterpolatedStringHandler
            {
                public FormatInterpolatedStringHandler(int literalLength, int formattedCount, nietras.SeparatedValues.SepWriter.Col col) { }
                public FormatInterpolatedStringHandler(int literalLength, int formattedCount, nietras.SeparatedValues.SepWriter.Col col, System.IFormatProvider? provider) { }
                public void AppendFormatted(System.ReadOnlySpan<char> value) { }
                public void AppendFormatted(string? value) { }
                public void AppendFormatted(System.ReadOnlySpan<char> value, int alignment = 0, string? format = null) { }
                public void AppendFormatted(object? value, int alignment = 0, string? format = null) { }
                public void AppendFormatted(string? value, int alignment = 0, string? format = null) { }
                public void AppendFormatted<T>(T value) { }
                public void AppendFormatted<T>(T value, int alignment) { }
                public void AppendFormatted<T>(T value, string? format) { }
                public void AppendFormatted<T>(T value, int alignment, string? format) { }
                public void AppendLiteral(string value) { }
            }
        }
        [System.Obsolete("Types with embedded references are not supported in this version of your compiler" +
            ".", true)]
        [System.Runtime.CompilerServices.CompilerFeatureRequired("RefStructs")]
        [System.Runtime.CompilerServices.IsByRefLike]
        public readonly struct Cols
        {
            public int Count { get; }
            public nietras.SeparatedValues.SepWriter.Col this[int colIndex] { get; }
            public void Format<T>(System.Collections.Generic.IReadOnlyList<T> values)
                where T : System.ISpanFormattable { }
            public void Format<T>([System.Runtime.CompilerServices.ParamCollection] [System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan<T> values)
                where T : System.ISpanFormattable { }
            public void Format<T>(System.Span<T> values)
                where T : System.ISpanFormattable { }
            public void Format<T>(T[] values)
                where T : System.ISpanFormattable { }
            public void Format<T>(System.ReadOnlySpan<T> values, nietras.SeparatedValues.SepWriter.ColAction<T> format) { }
            public void Set(System.Collections.Generic.IReadOnlyList<string> values) { }
            public void Set([System.Runtime.CompilerServices.ParamCollection] [System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan<string> values) { }
            public void Set(string[] values) { }
            public void Set(nietras.SeparatedValues.SepReader.Cols cols) { }
        }
        public delegate void ColAction(nietras.SeparatedValues.SepWriter.Col col);
        public delegate void ColAction<T>(nietras.SeparatedValues.SepWriter.Col col, T value);
        public delegate void RowAction(nietras.SeparatedValues.SepWriter.Row row);
    }
    public static class SepWriterExtensions
    {
        public static nietras.SeparatedValues.SepWriter To(this nietras.SeparatedValues.SepWriterOptions options, System.IO.Stream stream) { }
        public static nietras.SeparatedValues.SepWriter To(this nietras.SeparatedValues.SepWriterOptions options, System.IO.TextWriter writer) { }
        public static nietras.SeparatedValues.SepWriter To(this nietras.SeparatedValues.SepWriterOptions options, System.IO.Stream stream, bool leaveOpen) { }
        public static nietras.SeparatedValues.SepWriter To(this nietras.SeparatedValues.SepWriterOptions options, System.IO.TextWriter writer, bool leaveOpen) { }
        public static nietras.SeparatedValues.SepWriter ToFile(this nietras.SeparatedValues.SepWriterOptions options, string filePath) { }
        public static nietras.SeparatedValues.SepWriter ToText(this nietras.SeparatedValues.SepWriterOptions options) { }
        public static nietras.SeparatedValues.SepWriter ToText(this nietras.SeparatedValues.SepWriterOptions options, int capacity) { }
        public static nietras.SeparatedValues.SepWriterOptions Writer(this nietras.SeparatedValues.Sep sep) { }
        public static nietras.SeparatedValues.SepWriterOptions Writer(this nietras.SeparatedValues.SepSpec spec) { }
        public static nietras.SeparatedValues.SepWriterOptions Writer(this nietras.SeparatedValues.Sep sep, System.Func<nietras.SeparatedValues.SepWriterOptions, nietras.SeparatedValues.SepWriterOptions> configure) { }
        public static nietras.SeparatedValues.SepWriterOptions Writer(this nietras.SeparatedValues.SepSpec spec, System.Func<nietras.SeparatedValues.SepWriterOptions, nietras.SeparatedValues.SepWriterOptions> configure) { }
    }
    [System.Diagnostics.DebuggerDisplay("{DebuggerDisplay,nq}")]
    [System.Diagnostics.DebuggerTypeProxy(typeof(nietras.SeparatedValues.SepWriterHeader.DebugView))]
    public sealed class SepWriterHeader
    {
        public void Add(System.Collections.Generic.IReadOnlyList<string> colNames) { }
        public void Add([System.Runtime.CompilerServices.ParamCollection] [System.Runtime.CompilerServices.ScopedRef] System.ReadOnlySpan<string> colNames) { }
        public void Add(string colName) { }
        public void Add(string[] colNames) { }
        public void Write() { }
    }
    public readonly struct SepWriterOptions : System.IEquatable<nietras.SeparatedValues.SepWriterOptions>
    {
        public SepWriterOptions() { }
        public SepWriterOptions(nietras.SeparatedValues.Sep sep) { }
        public System.Globalization.CultureInfo? CultureInfo { get; init; }
        public nietras.SeparatedValues.Sep Sep { get; init; }
        public bool WriteHeader { get; init; }
    }
}