gpt4 book ai didi

c# - 由字段初始化引起的有害代码爆炸的真实示例是什么?

转载 作者:可可西里 更新时间:2023-11-01 09:12:45 26 4
gpt4 key购买 nike

CLR via C# 中,Richter 指出在类声明中初始化字段,就像这样

class C {
int x = 3;
int y = 4;

public C() { ... }
public C(int z) { ... }

...
}

导致在每个构造函数的开头插入语句,将字段设置为提供的值。因此,上面的 int x = 3; 行将负责两个单独的初始化——一个在无参数构造函数中,另一个在采用 int 参数的构造函数中。

里希特接着说:

This means that you should be aware of code explosion [...] If you have several initialized instance fields and a lot of overloaded constructor methods, you should consider defining the fields without the initialization, creating a single constructor that performs the common initialization, and having each constructor explicitly call the common initialization constructor. This approach will reduce the size of the generated code.

我无法想象这会成为一个值得注意的问题的场景,这让我想知道我是否遗漏了什么。例如,如果我们假设我们的类有 10 个构造函数和 100 个字段,并且它需要 16 个字节的本地机器代码来执行初始化,那么我们谈论的是总共 16 kB 的生成的本地代码。在本世纪以来的任何计算机上,这肯定是微不足道的内存量,对吧?

我认为使用泛型可以将其乘以一个小因子,但对工作集的影响似乎仍然很小。

问题:我是否遗漏了什么,如果遗漏了什么?

虽然我的问题主要是理论性的——我想测试我自己的理解——它也有点实际,因为初始化声明它们的字段似乎比使用像 Richter 建议的集中式构造函数产生的代码可读性要好得多.

最佳答案

What is a real-life example of detrimental code explosion caused by field initializations?

我不知道该问题的任何现实示例。

I'm having trouble envisioning a scenario in which this would become a noticeable issue

我也是。

which makes me wonder if I'm missing something here.

据我所知。

Surely that's a negligible amount of memory on any computer from this century, right?

没错。并且不要忘记,在一个困惑的世界中,您是为游戏付费的。您只能在调用时生成尽可能多的 ctors。

I imagine using generics could multiply that by a small factor

对于使用值类型构造的泛型类型,这通常是正确的。

but still the impact on the working set seems quite small.

再次强调,工作集是为游戏付费的。只被调用几次的代码最终会被换页,许多构造函数在程序中只被调用几次。

Am I missing something here, and, if so, what?

据我所知。

initializing the fields where they're declared seems to produce substantially more readable code than using a centralized constructor like Richter suggests.

我会首先针对正确性和优雅性进行优化,只有当经验性能测试清楚地表明这是一个真实的、影响用户的问题时,我才会解决这个问题。

关于c# - 由字段初始化引起的有害代码爆炸的真实示例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com