Skip to content

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

Closed

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.

Activity

  1. BillWagner commented on Nov 23, 2020

    @BillWagner
    Member

    Thanks for noting this @LokiMidgard

    This article does need an update for new features and optimizations available.

  2. self-assigned this
    on Feb 1, 2021
  3. added a commit that references this issue on Feb 23, 2021
    4f270c2
  4. added a commit that references this issue on Mar 3, 2021
    b2da32f
  5. added a commit that references this issue on Mar 24, 2021
    2a6dc59
  6. added a commit that references this issue on Apr 20, 2021
    a1c84bd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions