[C#] Improve Span<> utilization (#8588)

There are a couple instances where the ByteBuffer's Span property was accessed in a loop.
 + Extracted the use of the property outside of the loop to save a few cpu cycles.

Access to the allocator's internal buffer isn't exposed as a ReadOnlySpan<byte> from the ByteBuffer
or the FlatBufferBuilder.
 + Added a few convenience functions to access the buffer using a ReadOnlySpan<byte>.

There are a few cases where built in Span extensions can be used to run optimized code.
 + Added the use of Span.Fill() and ReadOnlySpan.SequenceCompareTo to replace existing loops.

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
This commit is contained in:
bigjt
2025-08-28 19:06:18 -04:00
committed by GitHub
parent a6b337f803
commit 82396fa0fe
3 changed files with 45 additions and 6 deletions

View File

@@ -183,6 +183,12 @@ namespace Google.FlatBuffers
var len_2 = bb.GetInt(offset_2);
var startPos_1 = offset_1 + sizeof(int);
var startPos_2 = offset_2 + sizeof(int);
#if ENABLE_SPAN_T && UNSAFE_BYTEBUFFER
var span_1 = bb.ToReadOnlySpan(startPos_1, len_1);
var span_2 = bb.ToReadOnlySpan(startPos_2, len_2);
return span_1.SequenceCompareTo(span_2);
#else
var len = Math.Min(len_1, len_2);
for(int i = 0; i < len; i++) {
byte b1 = bb.Get(i + startPos_1);
@@ -191,6 +197,7 @@ namespace Google.FlatBuffers
return b1 - b2;
}
return len_1 - len_2;
#endif
}
// Compare string from the ByteBuffer with the string object
@@ -200,6 +207,11 @@ namespace Google.FlatBuffers
var len_1 = bb.GetInt(offset_1);
var len_2 = key.Length;
var startPos_1 = offset_1 + sizeof(int);
#if ENABLE_SPAN_T && UNSAFE_BYTEBUFFER
ReadOnlySpan<byte> span = bb.ToReadOnlySpan(startPos_1, len_1);
ReadOnlySpan<byte> keySpan = key;
return span.SequenceCompareTo(keySpan);
#else
var len = Math.Min(len_1, len_2);
for (int i = 0; i < len; i++) {
byte b = bb.Get(i + startPos_1);
@@ -207,6 +219,7 @@ namespace Google.FlatBuffers
return b - key[i];
}
return len_1 - len_2;
#endif
}
}
}