关于c#优化器的问题

关于c#优化器的问题,c#,rename,optimization,C#,Rename,Optimization,如果我写: SomeType simpleName = classWithLongName.otherLongName; 然后使用“simpleName”而不是“classWithLongName.otherLongName”,这会以任何方式改变程序(例如性能方面) 编译器如何处理这个问题?它是否复制并粘贴“classWithLongName.otherLongName”,无论我在哪里使用“simpleName”。这取决于“otherLongName”实际上在做什么。如果它是一个属性,那么区别

如果我写:

SomeType simpleName = classWithLongName.otherLongName;
然后使用“simpleName”而不是“classWithLongName.otherLongName”,这会以任何方式改变程序(例如性能方面)


编译器如何处理这个问题?它是否复制并粘贴“classWithLongName.otherLongName”,无论我在哪里使用“simpleName”。

这取决于“otherLongName”实际上在做什么。如果它是一个属性,那么区别在于多次执行该属性还是只执行一次。这可能会也可能不会显著地改变程序的行为,这取决于程序正在执行的操作。

您始终可以将其设置为函数

SomeType simpleName() { return classWithLongName.otherLongName; }

只有当您始终键入“
classWithLongName.otherLongName
”时,编译器才允许缓存该值并重新使用它自己,前提是它知道该值在过程中不会更改。然而,这种情况很少发生

因此,如果“
classWithLongName.otherLongName
”确实执行了一些计算,您通常会按照建议将其手动缓存到局部变量中,从而获得更好的性能。但是,请记住,您使用的是缓存值,并且原始值或属性中的更改不会反映在缓存值上

但是,名称的长度只是元数据,对运行时性能没有任何影响,因为名称在编译期间已解析为内部句柄。

否,C#编译器不会将对“
simpleName
”的调用转换为与复制和粘贴“
classWithLongName.otherLongName
”相同的调用. 区别可能是深刻的,也可能只是语义上的,但您所做的是将classWithLongName.otherLongName中的值赋给simpleName。该类型是值类型还是引用类型将确切地确定发生了什么,以及如果您操作该值将发生什么,但您并不是在这样做时创建函数指针或委托


除了说它不会产生负面影响之外,它是否会对性能产生影响在这里真的不是什么可以回答的问题。我们不能说它是否会产生积极的影响,因为这取决于当您使用LongName.otherLongName调用
类时实际发生的情况。如果这是一个昂贵的操作,那么这可以使它更快,但缺点是后续调用
classWithLongName时会出现任何值差异。如果将其值缓存在
simpleName

中,则不会反映出其他LongName
的值。这是关于实例或类的问题吗

比如说

namespace MyCompany.MyApp.LongNamespaceName
{
    public class MyClassWithALongName {

        public SomeType AnInstanceProperty {get;set;}

        public static SomeType AStaticProperty {get { ... }}
    }
}
现在:

或者:

MyClassWithALongName anInstanceWithALongName = new MyClassWithALongName();

//this gets the instance property
SomeType simpleName = anInstanceWithALongName.AnInstanceProperty;
这些将以不同的方式表现

不过,这里还有另一种情况,您可以为类的实际名称创建别名:

using simpleName = MyCompany.MyApp.LongNamespaceName.MyClassWithALongName;

...
simpleName anInstance = new simpleName (); 
  • 如果classWithLongName.otherLongName是属性,则对simpleName的更改不会更改classWithLongName.otherLongName

  • 如果classWithLongName.otherLongName是值类型的公共数据成员(字段),则对simpleName的更改不会更改classWithLongName.otherLongName

  • 如果classWithLongName.otherLongName是引用类型的公共数据成员(字段),则对simpleName的更改将更改classWithLongName.otherLongName


假设您的类型是对象(引用)类型,那么simpleName最终将包含对classWithLongName.otherLongName返回的对象的引用。如果您随后要对该对象上的属性进行大量调用,那么您可能会获得性能改进,特别是如果otherLongName是一个属性而不是一个字段

using simpleName = MyCompany.MyApp.LongNamespaceName.MyClassWithALongName;

...
simpleName anInstance = new simpleName ();