Replies: 3 comments 10 replies
-
I'm assuming you're suggesting that something like: public byte[] GetBytes(string input)
{
// .... some code
return someByteArray;
} ... is being automagically converted to (in this case existing): public int GetBytes(ReadOnlySpan<char> input, Span<byte> output)
{
// whatever
} You can't, not in the general case. First, this requires deep introspection and rewriting of both the callee and the caller (remember, the caller would be required to pass in the destination span), which is maybe doable for some simple cases, but fails in a large number of edge cases. If the caller returns that byte array, the transformation can't be made. If the array element is a reference type (a class), the transformation can't be made.
You've picked possibly the worst method to use an example if this is one of your justifications. |
Beta Was this translation helpful? Give feedback.
-
No, the problem is that in most cases where a
Even ignoring
There's nothing inherently special about functional languages or styles in this area, the problem is more of a hardware/calling convention one.
You can't "return" stack allocated anything, especially anything dynamically sized, because doing so would require that you dynamically reorder the stack at runtime (and probably only allow one dynamically sized thing). Which would be an optimization and security problem. And for this to be really useful you'd need multiple levels of callers to do this, which would mean you'd have to copy parts of the stack as each level is unwound, which would possibly eliminate most of the savings. |
Beta Was this translation helpful? Give feedback.
-
I realized I can return stack allocated memory by using inline function in F# which is a different inlining method than C# in which it behaves like a macro |
Beta Was this translation helpful? Give feedback.
-
In any cases you are returning a span of stack allocated memory then use that memory in another function or in an imperative way with a variable, pretend that you've passed in the client that's using this memory as a function so you can access the stack allocated memory without it actually escaping the stack.
This makes no changes to how codes are written, but imagine System.Text.Encoding.UTF8.GetBytes(string) now returns Span that's not representing a region of memory in the heap therefore no allocation, which is impossible, unless we inline this function or we pass in a function that takes a span then we can use this span, so let's make the compiler to do this
This way, we will eliminate any memory being created in the heap when they are not too big for the stack, and with classes like Span people can still put the memory to heap by calling ToArray() for using the memory in another occasion, it's just that this would happen a lot less because you don't have to do it before returning stack allocated memory now
Beta Was this translation helpful? Give feedback.
All reactions