如果我寫:問題關於C#優化
SomeType simpleName = classWithLongName.otherLongName;
然後使用「simpleName」而不是「classWithLongName.otherLongName」,這會改變程序以任何方式(例如性能明智)?
編譯器用這個做什麼?它是否複製+粘貼「classWithLongName.otherLongName」,無處不在我使用「simpleName」。
如果我寫:問題關於C#優化
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。無論類型是值類型還是引用類型,都會確定發生了什麼,以及如果操縱該值會發生什麼,但是您不是在創建函數指針或委託。
是否會對性能產生影響真的不是在這裏可以回答的,除非說它不會產生負面影響。我們不能說它是否會產生積極影響,因爲這取決於您撥打classWithLongName.otherLongName
時發生的實際情況。如果這是一個昂貴的操作,那麼這可能會使速度更快,但缺點是,如果您在simpleName
中緩存了其值,則在後續調用classWithLongName.otherLongName
時,任何價值差異都不會反映出來。
這是關於實例或類的問題嗎?
例如
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();
如果classWithLongName.otherLongName是一個屬性,不是改變simpleName不會改變classWithLongName。 otherLongName。
如果classWithLongName.otherLongName是值類型的公共數據成員(字段),那麼對simpleName的更改將不會更改classWithLongName.otherLongName。
如果classWithLongName.otherLongName是引用類型的公共數據成員(字段),那麼對simpleName的更改將更改classWithLongName.otherLongName。
假設你的類型是一個對象(參考)輸入然後simpleName會因包含於由classWithLongName.otherLongName返回的對象的引用。如果您打算對該對象的屬性進行大量調用,那麼您可能會獲得性能改進,尤其是如果otherLongName是屬性而不是字段。
這產生了較大的影響。 – Jules 2009-04-20 14:44:06