C#C
C#3y ago
Samuel

❔ ✅ Splitting string without allocation

I'm writing a JsonConverter for Vector3 and I'd like to do this without allocating too much memory.

I've written this extension method to split the string as ReadOnlyMemory. I wanted to use ReadOnlySpan but I'm unable to use this type in IEnumerable<T>.
        public static IEnumerable<ReadOnlyMemory<T>> Split<T>(this ReadOnlyMemory<T> memory, T separator)
            where T: IEquatable<T>
        {
            int start = 0;
            int end = 0;
            while (end < memory.Length)
            {
                if (memory.Span[end].Equals(separator) || end == memory.Length)
                {
                    yield return memory.Slice(start, end - start);
                    start = end + 1;
                }                
                end++;
            }

        }

This is my implementation of Read for JsonConverter<Vector3>
public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
    ReadOnlyMemory<char> vectorString = reader.GetString().AsMemory();
    var vectorValues = vectorString.Split(',').Select(s => float.Parse(s)).ToArray(); // Unable to parse `s` as it's not a string. What do?
    return new Vector3 { X = vectorValues[0], Y = vectorValues[1], Z = vectorValues[2] };
}


I'd like to know if there are any ways to make my Split method better, and to somehow get my Read method to work.
Thanks for reading
Was this page helpful?