4

I was wondering what would be usage of the in keyword with ReadOnlyMemory<T> and ReadOnlySpan<T>.

void Method(ReadOnlyMemory<int> memory)
{
    // Code that modifies memory wont reflect out of this scope.
    memory = memory.Slice(3);
}

void Method(in Memory<int> memory)
{
    // same thing as the above
   memory.Slice(3);
}

void Method(in ReadOnlyMemory<int> memory)
{
    // is there any performance gain here or something?
}

Basically using in or ReadOnly (Span/Memory) isn't similar to const typename & (C++) ?

6
  • 5
    Race your horses and let us know
    – TheGeneral
    Commented May 24, 2018 at 7:09
  • 1
    The second one wouldn't even compile, would it?
    – Jon Skeet
    Commented May 24, 2018 at 8:27
  • Oh you are right for the second one. Commented May 24, 2018 at 8:45
  • All methods compile. The second and third though are flagged by the ErrorProne.NET analyzer as they'll result in defensive copies of the struct. Commented May 24, 2018 at 10:56
  • 1
    It is a micro-optimization, the struct gets passed by reference but it does not make the effort to copy the (possibly changed) value back to the caller. Not making the copy is a no-brainer, but you do need to find out if it is actually faster than passing by value, the normal way for small structs. The size of the struct and how often the struct members are addressed in the method body matter. It has only two members, so getting mileage out of in ought to be unlikely. You can get an accidental speedup by unintentionally forcing the jitter optimizer to make better choices. Commented May 24, 2018 at 12:38

0

Browse other questions tagged or ask your own question.