Skip to content

Mention how to mitigate performance issues with mutable structs and in parameter modifier #21691

@LokiMidgard

Description

@LokiMidgard

The Documentation says that using in parameters with mutable structs may lead to defensive copy's that decrease performance compared to a by-value approach.

However depending on the code a big struct may need to be modified often. Following advice would lead to performance decrease in those cases.

From what I'm understand if the method with the in parameter only calls readonly methods/properties and access only filed's on the struct it will not create a defensive copy. But it is not stated that explicitly.

However, the compiler can't know if any member method modifies the state of the struct. To ensure that the object isn't modified, the compiler creates a copy and calls member references using that copy. Any modifications are to that defensive copy.

This sounds to my like it will always copy the value if its not readonly struct, but profiling suggests otherwise.

I would like to have a list of does and don'ts if a immutable object is not an option in the documentation like following:

I'm don't know if the below is correct

The compiler will generate a defensive copy if any:

  • A method or property is called that is not marked with readonly
  • ...?

The compiler does not generate a defensive copy if you only:

  • access fields of the struct
  • call only methods and properties that are marked with readonly
  • pass the parameter to an method using an in parameter and that method will abides this rules
  • copy the struct to a local value

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions