with expression 与 new 关键字

with expression vs new keyword

我正在阅读关于 "what's new in C#9.0" 的 devblogs,然后我注意到 "with expression"。

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

他们说

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.

我的问题是, "with" 是否从 "Heap" 复制整个旧对象,然后用新值(如果存在)修改它们,然后创建新实例? (IMO ...我认为这是昂贵的方法) 还是 "with" 让你只写更少的行而没有任何内存泄漏?

如果我的第一个假设是正确的,那么使用 "with" 或 "new" 会更好,例如:var obj = new foo();

with 表达式创建了一个新实例,因此旧实例仍将保持不变,它不会发生变化——这是有道理的,因为其目的是处理不可变数据。

这不是内存泄漏,除非您以某种方式保留旧实例。它可能会增加 GC 流失,但这不一定是坏事,而且从不可变性推理中获得的收益通常值得付出代价。

(当然,我假设这里的编译器有优化的潜力,如果编译器可以证明旧值不会被使用,但我怀疑这样的事情是否已经实现——至少) .

编辑:

这里是 a SharpLab decompilation(为了使其正常工作,进行了一些更改)。你可以看到它编译成非常简单的东西。