beforefieldinitã®é襲
ã¡ãã£ã¨æã®ãã¿ã§ãã
http://d.hatena.ne.jp/akiramei/20051125/p1
éçã³ã³ã¹ãã©ã¯ã¿ãæ¸ãã¨beforefieldinitãä»ããªãã®ã§æã¿éãã®åä½ã«ãªãã¾ãã
ãã®ã¨ãã¯ãSingletonãã¿ã¼ã³ã®å®ç³ã¨ãã¦ç´¹ä»ãã¾ããããä¸ã®ä¸ãã¾ã話ã°ããã§ã¯ã»ã»ã»
以ä¸ã®ã³ã¼ããè¦ã¦ãã ãããClassã¨ClassWithStaticConstructorã®ï¼ã¤ã®ã¯ã©ã¹ãããã¾ããéãã¯éçã³ã³ã¹ãã©ã¯ã¿ããããç¡ããã§ãã
using System; class Class { static int number = 42; public static int Number { get { return number; } } } class ClassWithStaticConstructor { static int number; public static int Number { get { return number; } } static ClassWithStaticConstructor() { number = 42; } } class Program { const int LOOP = 100000000; static void Main(string[] args) { DateTime t0; t0 = DateTime.Now; for (int i = 0; i < LOOP; ++i) { int n = Class.Number; } Console.WriteLine(DateTime.Now.Subtract(t0)); t0 = DateTime.Now; for (int i = 0; i < LOOP; ++i) { int n = ClassWithStaticConstructor.Number; } Console.WriteLine(DateTime.Now.Subtract(t0)); } } /* çµæ 00:00:00.0468750 00:00:00.4843750 */
ãã³ããã¼ã¯ãåãã¨ä½ã¨10åãããå·®ãããã¾ãã使ç¨ãã寸åã¾ã§ã¤ã³ã¹ã¿ã³ã¹åãé 延ãããã³ã¹ããã¼ããªããã¯ç¡ãã£ãã¨ãããã¨ã§ããã(^^;
ã¾ããæ¥åç³»ã®ã¢ããªã§åé¡ã«ã¯ãªããªãã¨æãã¾ãããã²ã¼ã ãã°ã©ãã£ãã¯ã¹ç³»ãªããæèãã¦ããã¦æã¯ç¡ãããç¥ãã¾ãããã