0

如果我写:

SomeType simpleName = classWithLongName.otherLongName;

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

编译器对此做了什么?它是否在我使用“simpleName”的任何地方复制+粘贴“classWithLongName.otherLongName”。

4

7 回答 7

2

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

它是否会对性能产生影响真的不是这里可以回答的问题,只能说它不会产生负面影响。我们不能说它是否会产生积极影响,因为这取决于你打电话时实际发生的情况classWithLongName.otherLongName。如果这是一项昂贵的操作,那么这可能会使其更快,但缺点是classWithLongName.otherLongName如果您将其值缓存在simpleName.

于 2009-04-20T14:42:33.373 回答
1

这取决于“otherLongName”实际上在做什么。如果它是一个属性,那么区别在于执行该属性几次或只执行一次。这可能会或可能不会显着改变程序的行为,具体取决于它在做什么。

于 2009-04-20T14:37:33.307 回答
0

这是关于实例或类的问题吗?

例如

namespace MyCompany.MyApp.LongNamespaceName
{
    public class MyClassWithALongName {

        public SomeType AnInstanceProperty {get;set;}

        public static SomeType AStaticProperty {get { ... }}
    }
}

现在:

//this gets the static property
SomeType simpleName = MyClassWithALongName.AStaticProperty;

或者:

MyClassWithALongName anInstanceWithALongName = new MyClassWithALongName();

//this gets the instance property
SomeType simpleName = anInstanceWithALongName.AnInstanceProperty;

这些将以不同的方式表现。

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

using simpleName = MyCompany.MyApp.LongNamespaceName.MyClassWithALongName;

...
simpleName anInstance = new simpleName (); 
于 2009-04-20T14:54:08.990 回答
0

classWithLongName.otherLongName如果编译器知道该值在课程中不会改变,则只有在您始终键入“”时,才允许编译器缓存该值并自行重新使用它。但是,这种情况很少见。

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

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

于 2009-04-20T14:41:01.847 回答
0
  • 如果 classWithLongName.otherLongName 是一个属性,那么对 simpleName 的更改将不会更改 classWithLongName.otherLongName。

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

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

于 2009-04-20T15:11:29.823 回答
0

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

于 2009-04-20T15:12:04.860 回答
-1

你总是可以让它成为一个函数。

SomeType simpleName() { return classWithLongName.otherLongName; }
于 2009-04-20T14:39:13.160 回答