From 913c4307d6cf8ca070cb980bc3b122e4c2e7eb0a Mon Sep 17 00:00:00 2001 From: Erik Edespong Date: Sun, 25 Nov 2018 13:21:32 +0100 Subject: [PATCH] Issue #63 - Do not warn on foreach over string --- .../EnumeratorAllocationAnalyzerTests.cs | 11 +++++++++++ .../EnumeratorAllocationAnalyzer.cs | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/ClrHeapAllocationsAnalyzer.Test/EnumeratorAllocationAnalyzerTests.cs b/ClrHeapAllocationsAnalyzer.Test/EnumeratorAllocationAnalyzerTests.cs index 2d80e3d..ec8a652 100644 --- a/ClrHeapAllocationsAnalyzer.Test/EnumeratorAllocationAnalyzerTests.cs +++ b/ClrHeapAllocationsAnalyzer.Test/EnumeratorAllocationAnalyzerTests.cs @@ -119,5 +119,16 @@ private IEnumerator GetIEnumeratorViaIEnumerable() // Diagnostic: (11,35): warning HeapAnalyzerEnumeratorAllocationRule: Non-ValueType enumerator may result in a heap allocation *** AssertEx.ContainsDiagnostic(info.Allocations, id: EnumeratorAllocationAnalyzer.ReferenceTypeEnumeratorRule.Id, line: 11, character: 35); } + + [TestMethod] + public void EnumeratorAllocation_IterateOverString_NoWarning() + { + var sampleProgram = "foreach (char c in \"foo\") { }"; + + var analyser = new EnumeratorAllocationAnalyzer(); + var info = ProcessCode(analyser, sampleProgram, ImmutableArray.Create(SyntaxKind.ForEachStatement)); + + Assert.AreEqual(0, info.Allocations.Count); + } } } diff --git a/ClrHeapAllocationsAnalyzer/EnumeratorAllocationAnalyzer.cs b/ClrHeapAllocationsAnalyzer/EnumeratorAllocationAnalyzer.cs index b3e124e..8c7c9a9 100644 --- a/ClrHeapAllocationsAnalyzer/EnumeratorAllocationAnalyzer.cs +++ b/ClrHeapAllocationsAnalyzer/EnumeratorAllocationAnalyzer.cs @@ -33,6 +33,13 @@ protected override void AnalyzeNode(SyntaxNodeAnalysisContext context) if (typeInfo.Type == null) return; + if (typeInfo.Type.Name == "String" && typeInfo.Type.ContainingNamespace.Name == "System") + { + // Special case for System.String which is optmizined by + // the compiler and does not result in an allocation. + return; + } + // Regular way of getting the enumerator ImmutableArray enumerator = typeInfo.Type.GetMembers("GetEnumerator"); if ((enumerator == null || enumerator.Length == 0) && typeInfo.ConvertedType != null)