From a44bf8a47332359a0dbe2745239ee0dad48a5941 Mon Sep 17 00:00:00 2001 From: Bruce Bowyer-Smyth Date: Sat, 21 Nov 2015 06:50:12 +1000 Subject: [PATCH] Return existing string instance for String.Join when there is only one item in the list --- .../src/System/String.cs | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/System.Private.CoreLib/src/System/String.cs b/src/System.Private.CoreLib/src/System/String.cs index 1e186d432d6..4c02efe3992 100644 --- a/src/System.Private.CoreLib/src/System/String.cs +++ b/src/System.Private.CoreLib/src/System/String.cs @@ -421,29 +421,28 @@ public static String Join(String separator, IEnumerable values) if (values == null) throw new ArgumentNullException("values"); - if (separator == null) - separator = String.Empty; - - using (IEnumerator en = values.GetEnumerator()) { if (!en.MoveNext()) return String.Empty; - StringBuilder result = StringBuilderCache.Acquire(); - if (en.Current != null) + String firstValue = en.Current; + + if (!en.MoveNext()) { - result.Append(en.Current); + // Only one value available + return firstValue ?? String.Empty; } - while (en.MoveNext()) + // Null separator and values are handled by the StringBuilder + StringBuilder result = StringBuilderCache.Acquire(); + result.Append(firstValue); + + do { result.Append(separator); - if (en.Current != null) - { - result.Append(en.Current); - } - } + result.Append(en.Current); + } while (en.MoveNext()); return StringBuilderCache.GetStringAndRelease(result); } } @@ -476,6 +475,11 @@ public unsafe static String Join(String separator, String[] value, int startInde return String.Empty; } + if (count == 1) + { + return value[startIndex] ?? String.Empty; + } + int endIndex = startIndex + count - 1; StringBuilder result = StringBuilderCache.Acquire(); // Append the first string first and then append each following string prefixed by the separator.