Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.

Commit

Permalink
Merge pull request #1460 from bbowyersmyth/StringJoin
Browse files Browse the repository at this point in the history
String.Join optimization for single item lists
  • Loading branch information
AlexGhiondea committed Sep 17, 2015
2 parents 5c3324b + c81320a commit d176041
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions src/mscorlib/src/System/String.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,27 +159,27 @@ public static String Join(String separator, IEnumerable<String> values) {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();

if (separator == null)
separator = String.Empty;


using(IEnumerator<String> en = values.GetEnumerator()) {
if (!en.MoveNext())
return String.Empty;

StringBuilder result = StringBuilderCache.Acquire();
if (en.Current != null) {
result.Append(en.Current);
String firstValue = en.Current;

if (!en.MoveNext()) {
// 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);
}
}
}


Expand Down Expand Up @@ -219,13 +219,19 @@ public unsafe static String Join(String separator, String[] value, int startInde
if (count == 0) {
return String.Empty;
}


if (count == 1) {
return value[startIndex] ?? String.Empty;
}

int jointLength = 0;
//Figure out the total length of the strings in value
int endIndex = startIndex + count - 1;
for (int stringToJoinIndex = startIndex; stringToJoinIndex <= endIndex; stringToJoinIndex++) {
if (value[stringToJoinIndex] != null) {
jointLength += value[stringToJoinIndex].Length;
string currentValue = value[stringToJoinIndex];

if (currentValue != null) {
jointLength += currentValue.Length;
}
}

Expand Down

0 comments on commit d176041

Please sign in to comment.