with expression vs new keyword

一个人想着一个人 提交于 2020-06-29 06:45:18

问题


I was reading the devblogs about "what's new in C#9.0", then I noticed "with expression".

public data class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}
var otherPerson = person with { LastName = "Hanselman" };

they say

A record implicitly defines a protected “copy constructor” – a constructor that takes an existing record object and copies it field by field to the new one:

protected Person(Person original) { /* copy all the fields */ } // generated

The with expression causes the copy constructor to get called, and then applies the object initializer on top to change the properties accordingly.

My question is , Does "with" copy the whole old objects from "Heap" and then modify them with new values (if exists) and then make new instance? (IMO...I think this is expensive approach) or Does "with" make you write less lines ONLY without any memory leaks?

if my first assumption were right, would it be better to use "with" or "new" like: var obj = new foo();


回答1:


A with expression creates a new instance, so the old instance will still exist unchanged, it does no mutation—this makes sense, given the intent is for working with immutable data.

This is not a memory leak, unless you keep the old instances around somehow. It may increase GC churn, but that isn't necessarily a bad thing, and the gains in the ease of reasoning from immutability can often be worth that cost.

(Of course, I assume there is potential for optimization from the compiler here, if the compiler can prove the old value won't be used, but I doubt such a thing is implemented—yet at the very least).

Edit:

Here is a SharpLab decompilation (with a few changes to get it working). You can see that it is quite simple stuff it compiles down to.



来源:https://stackoverflow.com/questions/62418120/with-expression-vs-new-keyword

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!