BagTests.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using MonoGame.Extended.Collections;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Runtime;
  6. using System.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using Xunit;
  9. namespace MonoGame.Extended.Tests.Collections
  10. {
  11. public class BagTests
  12. {
  13. [Fact]
  14. public void Bag_Enumeration_Does_Not_Allocate()
  15. {
  16. var bag = new Bag<int>();
  17. for (int i = 0; i < 100; i++) bag.Add(i);
  18. // ensure we have plenty of memory and that the heap only increases for the duration of this test
  19. Assert.True(GC.TryStartNoGCRegion(Unsafe.SizeOf<Bag<int>.BagEnumerator>() * 1000));
  20. var heapSize = GC.GetAllocatedBytesForCurrentThread();
  21. // this should NOT allocate
  22. foreach (int i in bag)
  23. {
  24. // assert methods cause the NoGCRegion to fail, so do this manually
  25. if (GC.GetAllocatedBytesForCurrentThread() != heapSize)
  26. Assert.True(false);
  27. }
  28. // sanity check: this SHOULD allocate
  29. foreach (int _ in (IEnumerable<int>)bag)
  30. {
  31. // assert methods cause the NoGCRegion to fail, so do this manually
  32. if (GC.GetAllocatedBytesForCurrentThread() == heapSize)
  33. Assert.True(false);
  34. }
  35. // Wrap in if statement due to exception thrown when running test through
  36. // cake build script or when debugging test script manually.
  37. if(GCSettings.LatencyMode == GCLatencyMode.NoGCRegion)
  38. {
  39. GC.EndNoGCRegion();
  40. }
  41. }
  42. }
  43. }