.NET GC & Memory (2)
ä¸ã® 2 ã¤ã® GDNJ ã®ã¹ã¬ããã§ãã¡ãã»ãè¨åããã¦ãã¾ããï¼ç¾å¨ã® CLR å®è£
ã§ã¯ 85000 byte 以ä¸ã®ãªãã¸ã§ã¯ã㯠Large Object Heap (LOH) ã«ç¢ºä¿ããï¼ãããªã第äºä¸ä»£æ±ãã§å§ã¾ã£ããã³ã³ãã¯ã·ã§ã³ãè¡ãããªãã£ããã¨è²ã
ç¹å¥æ±ããåãããã¨ã«ãªãã¾ãï¼å®éï¼ä¸ã®ã³ã¼ããèµ°ããã¦ã¿ãã¨ç¬¬äºä¸ä»£ GC ã®åæ°ãã¨ãã§ããªãå¤ããã¨ã«æ°ä»ããã¨æãã¾ãï¼
ã¤ã¾ãä¸ã®ã³ã¼ãã¯ï¼ãé常 0 ä¸ä»£ç®ã® GC ãé »çºãããã¨ããä»®å®ãæãç«ããªãï¼ããªãç¹æ®ãªç¶æ³ãè¦ã¦ãããã¨ã«ãªãã¾ãï¼ä¼¼ããããªã³ã¼ãã¯æã
ãç®ã«ããããã¨ããã£ã¦ï¼ä¾ãã°ä»¥å id:Kazzz ãããç´¹ä»ããã¦ãããã³ããã¼ã¯è¨äºãããã ã£ãããã¾ãï¼
NyaRuRu ããã¼ã¨ï¼å¾®å¦ã«é·ã話ãè²ã æ¸ããããªããããªãã³ããã¼ã¯ã§ããªï¼ (ãããã°ãã«ããã¡ãã㨠IsJITTrackingEnabled ã¨ã IsJITOptimizerDisabled ãä»ãã¡ããããããªãã¨ã (Essential .NET 10.5) ï¼n^2 ã§æåæ°ãå¢ãã¦ããã¨ããã¨ã)
ç´¹ä»ããããªã³ã¯å ã§ä¾ã¨ãã¦æãããã¦ããã®ã¯ï¼æ¬¡ã®ãããªã³ã¼ãã§ããï¼
// Test1 string str = string.Empty; for (int i = 0; i < times; i++) { str += i.ToString(); }
ãã®ã«ã¼ãã§ã¯æ¦ã n^2 ã®ãªã¼ãã¼ã§æåæ°ãå¢ãã¦ããï¼i == 10721 ããã㧠42500 æåãä¸åãã¾ã*1ï¼
"" "" + "0" "0" + "1" "01" + "2" "012" + "3" "0123" + "4" ... "0123...10720" + "10721"
ãã®ãã³ããã¼ã¯ã¯ï¼åã« + æ¼ç®åã§æååçæãç¹°ãè¿ãã¨ããã ãã§ãªãï¼çæããããªãã¸ã§ã¯ããéä¸ãã LOH ã«ç¢ºä¿ãããã»ã©å¤§ãããªãã¨ããç¹æ®æ§ãæã£ã¦ãã¾ãï¼
æ¯è¼ã®ããã«ï¼ã¡ã¢ãªå¨ãã«æ³¨ç®ãã¦ä¼¼ããããªã¡ã¢ãªè² è·ãæå³ãã Test2 ãä½ã£ã¦ã¿ã¾ããï¼
// Test2 int length = 0; for (int i = 0; i < times; i++) { length += (int)Math.Log10(i + 1) + 1; char[] buf = new char[length]; // æé©åã§é¤å»ãããªãããã«ã¢ã¯ã»ã¹ãè¡ã buf[0] = '0'; }
ããã«ï¼ã½ãããã¼ã¸ãã©ã«ããå ¨é åã«èµ·ããã¹ã*2ããå°ãã¡ã¢ãªã¢ã¯ã»ã¹éãå¢ããããã®ã Test3 ã§ãï¼
// Test3 int length = 0; for (int i = 0; i < times; i++) { length += (int)Math.Log10(i+1)+1; char[] buf = new char[length]; // ã¾ããã«å ¨ãã¼ã¸ã§ãã¼ã¸ãã©ã«ããçºçããã for( int l = 0; l < length; l += 2048 ) { buf[l] = '0'; } }
ããã«æ¯è¼ç¨ã«ï¼ç¢ºä¿ããã¡ã¢ãªå ¨é¨ã 0 ã¯ãªã¢ãã Test4 ã§ãï¼
// Test4 int length = 0; for (int i = 0; i < times; i++) { length += (int)Math.Log10(i + 1) + 1; char[] buf = new char[length]; // æ¯è¼ç¨ã«å ¨ã¦ 0 ã¯ãªã¢ããã¦ã¿ã for (int l = 0; l < length; ++l) { buf[l] = '0'; } }
ãã¦ï¼æå ã®ç°å¢*3ã§ã®å®è¡çµæã§ããï¼ãããªæãã«ãªãã¾ããï¼
ãã¹ã | çµéæé | Gen0 GC | Gen1 GC | Gen2 GC | ãã¼ã¸ãã©ã«ã |
---|---|---|---|---|---|
Test1 | ç´ 144 ç§ | 33,914 | 33,423 | 33,359 | 4,489,941 |
Test2 | ç´ 6 ç§ | 34,869 | 33,359 | 33,359 | 82,181 |
Test3 | ç´ 55 ç§ | 34,869 | 33,359 | 33,359 | 10,380,720 |
Test4 | ç´ 112 ç§ | 34,869 | 33,359 | 33,359 | 10,437,881 |
ãªãã¨ãããï¼ããã ãä¼ç·ãå¼µã£ã¦ãã㦠GC å¨ããå®è¡æéã«ä¸ããå½±é¿ã¯çµæ§å¾®å¦ã¨ããã®ã¨ï¼ãªã«ãã«ã½ãããã¼ã¸ãã©ã«ãå¨ãã ãã§ããããã®æéãæ¶è²»ãã¦ããçããããã¨ããçµæã§ãï¼ã¾ããããããã¨ããããã楽ããããã§ããã©ï¼
Test2ï¼Test3ï¼Test4 ã®å·®ãªããã .NET ã®ä¸çã ãã§èª¬æãããã¨ããã¨æ¬å½ã«æ³¥æ²¼ã«åµã£ã¦ãã¾ãããããªããã¨æãã¾ãï¼ã«ã¼ãåæ°ã¯ 2048 åã«å¢ããã®ã«ï¼æ¶è²»æé㯠2 åã¡ãã£ã¨ããå¢ããªãã¨ããã®ã¯ï¼ã½ã¼ã¹ã³ã¼ãã ããè¦ã¦æ¨æ¸¬ãå·¡ããã¨ããã¢ããã¼ãããè¦ãã°ååãããã¨ããã§ãããï¼
ãªãã¨ãããï¼ããã¬ã¤ã¤ã¼ã§ãã£ã¨ããããç¯äººãã§ã£ã¡ããã¦ã¿ããï¼ä¸æ®µä¸ã®ã¬ã¤ã¤ã¼æãã§ã¯èª¬æãã¤ããªãç¾è±¡ãã¡ãã»ãè¦ãé ãããä¾ï¼ã¨ãããã¨ã§ï¼