-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Description
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
inparameter 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.
- ID: ac8804c7-6acd-ab2a-4e14-0b99265969a5
- Version Independent ID: 183efcbd-a781-d303-f9cd-1c22da1676de
- Content: Write safe and efficient C# code
- Content Source: docs/csharp/write-safe-efficient-code.md
- Product: dotnet-csharp
- Technology: csharp-advanced-concepts
- GitHub Login: @BillWagner
- Microsoft Alias: wiwagn