Span vs. MemorySegment

John Rose john.r.rose at oracle.com
Thu Aug 8 19:17:13 UTC 2019


Here’s a quick comparison of the Microsoft “Span<T>” type [1] vs. the Panama MemorySegment type [2].

[1]: https://docs.microsoft.com/en-us/dotnet/api/system.span-1?view=netstandard-2.1

[2]: http://cr.openjdk.java.net/~mcimadamore/panama/memaccess_javadoc/jdk/incubator/foreign/MemorySegment.html

Corrections invited.

Differences:

MS is untyped, and sized in bytes, like a ByteBuffer.  Span<T> is a sequence of T, like an X-Buffer.

Span has a richer set of logical operations for searching and comparison, such as ToString, Equals, StartsWith.  In this it is like CharSequence or String or the jul.Arrays methods.

Span has more sugary tie-ins to arrays and array-like notations, such as for-loop integration, operator[], and implicit conversion from T[] to Span<T>.

MS uses a dynamic liveness check to enforce temporal confinement (avoiding use-after-free); this requires special optimizer logic but no special language rules.
Span uses special language rules to statically confine span access to the defining stack frame and its callees.  These rules also interact with the “unsafe” status of code blocks.

Span supports low-level copy operations, CopyTo and TryCopyTo.  This seems like a good option for MS as well.

Similarities:

Both are contiguous.  There is no virtualized scatter/gather; you can only “slice” a larger sequence, not combine two smaller ones.

Both are designed to support provably safe access to underlying storage, via spatial and temporal confinement checks.

Both support (spatial) bounds checking as a runtime check throwing some kind of IndexOutOfRangeException.

Temporal and spatial bounds checking can be turned off with sufficient privilege.  (The details differ between MS and Span.)

Both support read-only views.

Both are designed to support divide-and-conquer multiprocessing algorithms.



More information about the panama-dev mailing list