Hacker News new | ask | show | jobs
by neonsunset 636 days ago
Do Go slices make it more complex? :)

Span<T> makes the language simpler from both the user and C# to IL bytecode point of view, all the complexity is in the runtime (well, not exactly anymore - there's ref T lifetime analysis now). On that note, Java does not seem to have a generic slice type, like ArraySegment<T> which predates spans. I can see it has ByteBuffer, CharBuffer, IntBuffer, AbstractEnterpriseIntProviderFactoryBuffer (/s), etc from NIO as well as sub-Lists(?) and using Streams in the style of LINQ's Skip+Take.

Spans are very easy to use, and advertising them as advanced type was a short-lived mistake at their inception. Since then, they have gotten adopted prominently throughout the ecosystem.

After all, it's quite literally just

  var text = "Hello, World!".AsSpan();
  var hello = text[..text.IndexOf(','));
  var twoChars = hello[..2];
And, to emphasize, they transparently work with stack buffers, arrays, unmanaged memory and anything in-between. You can even reference a single field from an object:

    var user = (Name: "John", DoB: new DateTime(1989, 1, 1));
    ProcessStrings(new(ref user.Name));

    // Roslyn emits an inline array struct, from which a span is constructed
    // It's like T... varargs in Java but guaranteed zero-cost
    // In C# 13, this gets support of params so many existing callsites
    // that used to be params T[] start accepting spans instead,
    // completely eliding allocations or even allowing the compiler
    // to reference baked into binary constant arrays
    ProcessStrings(["hello", "world"]);

    void ProcessStrings(Span<string> values) { /* ... */ }
On binary-trees - indeed, the results are interesting and Java demonstrates consistently lower CPU time cost to achieve similar or higher throughput (look at benchmark results distribution). It is a stress-test for allocation and collection throughput, yes. However, Java benchmarks also tend to consume consistently more memory even in allocatey scenarios: https://benchmarksgame-team.pages.debian.net/benchmarksgame/...

In any case, I have asked around for more data on detailed comparison of heap profiles between G1, Zgc and Parallel and will post them here if I get a response to provide more context. It's an interesting topic.