Read-only struct as return parameter

Viewed 185

I am looking at implementing an async function returning a result struct, the result itself should be immutable and i am considering returning an read-only struct instead of class.

Looking at some latest Microsoft apis source code i can see that read-only structs are widely used so my question is whether this would be the correct way to go. From reading numerous articles this is not clear, many point out that struct should be only used for small size values? Since struct will be read-only as i understand there will be no copying ? My return structure will have 2-5 int values and a reference to ReadOnlyMemory buffer.

The purpose is of course to have most efficient low memory footprint code.

Thanks.

1 Answers

That's perfectly valid, certainly. As you seem to know, the struct part helps avoid some allocations, and the readonly part avoids all the pain commonly associated with mutable value-types. As a return value, I wouldn't even hesitate - it's fine. As an input to a "sync" method, you might want to consider adding the in modifier so that a large value-type isn't unnecessarily copied on the stack (which can otherwise make value-types more expensive than reference-types). However, in your specific case the "async" is often going to be a barrier to in usage (you can't use in and async in combination). For genuinely understanding whether using a struct makes it faster, you need to benchmark your specific scenario, as the details matter a lot.

You might also need to be aware of the allocation scenarios in async code. For example, you might want to think about ValueTask<T> results (rather than Task<T> results), and if the result is commonly synchronous (and occasionally truly async), optimizing for that to avoid the state machine - which can be summarised by this approach. Depending on the scenario, you might also want to play with tools like PooledAwait (which is available on NuGet).

Related