by c-smile · 8y ago · 0 comments
> (Span<T> is) at the heart of most performance-related improvements in .NET Core 2.1. Since it allows managing buffers in a more efficient way, it can help in reducing allocations and copying. We consider Span to be a very fundamental type as it requires runtime and compiler support in order to be fully leveraged.
Small struct that is declared as
public readonly ref struct Span<T>
{
private readonly ref T _pointer;
private readonly int _length;
...
}
which is exactly what I am using in Sciter (https://sciter.com) for 10+ years: template <typename T>
struct slice {
const T* start;
unsigned int length;
...
}
https://github.com/c-smile/sciter-sdk/blob/master/include/au...Such small thing definitely speed ups many areas and surprisingly quite a lot, parsing in particular.
Nothing new under the Sun, eh?
I get it, similar concepts - but let's not dismiss the value in this addition.
It reincarnated quite many times: in D language by Walter Bright where arrays are just such slices. Or by Andrei Alexandrescu in its range<T> thing: http://www.informit.com/articles/article.aspx?p=1407357&seqN...
It is used strictly in read-only places. It makes absolutely no sense to use things like std::string (and allocate it each time) when you need to pass string or fragment of string or array to consumers.
For write-only access I also have target<T> that safely wraps all memcpy, memmove, strcpy[_s] cases.
public readonly ref struct Span<T>
{
private readonly ref T _pointer;
private readonly int _length;
...
}
But the important parts are not _pointer or _length. Most of the implementation effort went into the `ref struct` part, which was released at the same time as Span<T> and is precisely what makes Span<T> powerful. It is a big thing.The Slice is just an address of memory chunk combined with the length of that chunk. That's somehow better than "C strings" - that are just pointers and so you need to do some computation if you need to get length of the string. Such C strings have too many drawbacks - in particular strtok function that modifies input string (that shall be read only all times).
And I bet Sciter is younger than any of them.
Modula-3 version:
GENERIC MODULE Slices(T)
TYPE
Slice = RECORD
start : REF T; (* If you want the GC out of the way, replace with UNTRACED REF T*)
length: CARDINAL;
...
END;
END Slices;
Or one could simply use open arrays: TYPE
Slice = ARRAY OF T
Eiffel version: expanded class Slice[T]
start: detachable T;
length: INTEGER_32;
...
end
Naturally, one would use Array[T].slice() instead.http://smarteiffel.loria.fr/libraries/api/lib.d/storage.d/lo...