ÕâЩÀàÐ͵ļ¯ºÏ¸Ä½øÀ©Õ¹²»½ö½öÊÇSystem.Collections.GenericÃüÃû¿Õ¼ä; System.Collections.ConcurrentÒ²Óкܶà¸Ä½ø¡£ÊÂʵÉÏ£¬.NET Core 2.0ÉϵÄConcurrentQueue <T>ºÍConcurrentBag <T>ÍêÈ«ÖØдÁË¡£ÏÂÃæ¿´¿´Ò»¸ö»ù±¾µÄÀý×Ó£¬Ê¹ÓÃConcurrentQueue <T>µ«Ã»ÓÐÈκβ¢·¢£¬Àý×ÓÖÐʹÓÃConcurrentQueue <T>´úÌæÁËQueue<T>£º
using System; using System.Diagnostics; using System.Collections.Concurrent; public class Test { Main() { while (true) { var q = new ConcurrentQueue<int>(); var sw = Stopwatch.StartNew(); for (int i = 0; i < 100_000_000; i++) { q.Enqueue(i); q.TryDequeue(out int _); } Console.WriteLine(sw.Elapsed); } } }
ÔÚ¸öÈ˵çÄÔÉÏ£¬.NET 4.7²úÉúµÄÊä³öÈçÏ£º
£º£º00£º02.6255135
ÏÔÈ»£¬.NET 4.7ÉϵÄConcurrentQueue <T>ʾÀý±È.NET 4.7ÖеÄQueue <T>°æ±¾Âý£¬ÒòΪConcurrentQueue <T>ÐèÒª²ÉÓÃͬ²½À´È·±£ÊÇ·ñ°²È«Ê¹Óᣵ«ÊÇ£¬¸üÓÐȤµÄ±È½ÏÊǵ±ÔÚ.NET Core 2.0ÉÏÔËÐÐÏàͬµÄ´úÂëʱ»á·¢Éúʲô£º
£º£º00£º01.7560811
Õâ±íÃ÷µ±½«.NET Core 2.0Çл»µ½30£¥Ê±£¬ConcurrentQueue <T>µÄÍÌÍÂÁ¿Ã»ÓÐÈκβ¢·¢ÐÔÌá¸ß¡£µ«ÊÇʵʩÖеı仯Ìá¸ßÁËÐòÁл¯µÄÍÌÍÂÁ¿£¬ÉõÖÁ¸ü¶àµØ¼õÉÙÁËʹÓöÓÁеÄÉú²úºÍÏûºÄÖ®¼äµÄͬ²½£¬Õâ¿ÉÄܶÔÍÌÍÂÁ¿ÓиüÃ÷ÏÔµÄÓ°Ïì¡£Ç뿼ÂÇÒÔÏ´úÂ룺
using System; using System.Diagnostics; using System.Collections.Concurrent; using System.Threading.Tasks; public class Test { Main() { while (true) { const int Items = 100_000_000; var q = new ConcurrentQueue<int>(); var sw = Stopwatch.StartNew(); Task consumer = Task.Run(() => { int total = 0; while (total < Items) if (q.TryDequeue(out int _)) total++; }); for (int i = 0; i < Items; i++) q.Enqueue(i); consumer.Wait(); Console.WriteLine(sw.Elapsed); } } }
ÔÚ.NET 4.7ÖУ¬¸öÈ˼ÆËã»úÊä³öÈçϽá¹û£º
£º£º00£º06.6069291
¶øʹÓÃ.NET Core 2.0£¬»áµÃµ½ÒÔϽá¹û£º
£º£º00£º01.4927520
ÕâÊÇÒ»¸ö3.5±¶µÄÍÌÍÂÁ¿µÄÔö³¤¡£²»µ«CPUЧÂÊÌá¸ßÁË£¬ ¶øÇÒÄÚ´æ·ÖÅäÒ²´ó´ó¼õÉÙ¡£ÏÂÃæµÄÀý×ÓÖ÷Òª¹Û²ìGC¼¯ºÏµÄÊýÁ¿£¬¶ø²»ÊǹÒÖÓʱ¼ä£º
using System; using System.Diagnostics; using System.Collections.Concurrent; public class Test { Main() { while (true) { var q = new ConcurrentQueue<int>(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); for (int i = 0; i < 100_000_000; i++) { q.Enqueue(i); q.TryDequeue(out int _); } Console.WriteLine($); } } }
ÔÚ.NET 4.7ÖУ¬µÃµ½ÒÔÏÂÊä³ö£º
Gen0 = 162 Gen1 = 80 Gen2 = 0 Gen0 = 162 Gen1 = 81 Gen2 = 0 Gen0 = 162 Gen1 = 81 Gen2 = 0 Gen0 = 162 Gen1 = 81 Gen2 = 0 Gen0 = 162 Gen1 = 81 Gen2 = 0
¶øʹÓÃ.NET Core 2.0£¬»áµÃµ½ÈçÏÂÊä³ö£º
Gen0 = 0 Gen1 = 0 Gen2 = 0 Gen0 = 0 Gen1 = 0 Gen2 = 0 Gen0 = 0 Gen1 = 0 Gen2 = 0 Gen0 = 0 Gen1 = 0 Gen2 = 0 Gen0 = 0 Gen1 = 0 Gen2 = 0
.NET 4.7ÖеÄʵÏÖʹÓÃÁ˹̶¨´óСµÄÊý×éÁ´±í£¬Ò»µ©¹Ì¶¨ÊýÁ¿µÄÔªËر»Ìí¼Óµ½Ã¿¸öÊý×éÖУ¬¾Í»á±»¶ªÆú£¬ ÕâÓÐÖúÓÚ¼ò»¯ÊµÏÖ£¬µ«Ò²»áµ¼ÖÂÉú³É´óÁ¿À¬»ø¡£ÔÚ.NET Core 2.0ÖУ¬ÐµÄʵÏÖÈÔȻʹÓÃÁ´½ÓÔÚÒ»ÆðµÄÁ´½ÓÁÐ±í£¬µ«ÊÇËæ×ÅеÄƬ¶ÎµÄÌí¼Ó£¬ÕâЩƬ¶ÎµÄ´óС»áÔö¼Ó£¬¸üÖØÒªµÄÊÇʹÓÃÑ»·»º³åÇø£¬Ö»ÓÐÔÚÇ°Ò»¸öƬ¶ÎÍêÈ«½áÊøʱ£¬ÐÂƬ¶Î²Å»áÔö¼Ó¡£ÕâÖÖ·ÖÅäµÄ¼õÉÙ¿ÉÄܶÔÓ¦ÓóÌÐòµÄÕûÌåÐÔÄܲúÉúÏ൱´óµÄÓ°Ïì¡£
¡¡