Skip to content

Commit

Permalink
Simplified std.array.join with separator.
Browse files Browse the repository at this point in the history
Previously, std.array.join with a separator would check whether it needed to add the separator on each iteration of the loop. With this change, the check is unnecessary because the first element is appended before the loop, then the loop just adds the separator and next element each iteration.

This improves the code significantly in the case of a non-forward RoR because we don't need to know the length anymore. It's simpler, and will be slightly faster.
  • Loading branch information
Poita committed Dec 25, 2012
1 parent bbcd9a5 commit 25abd87
Showing 1 changed file with 11 additions and 29 deletions.
40 changes: 11 additions & 29 deletions std/array.d
Expand Up @@ -1511,18 +1511,16 @@ ElementEncodingType!(ElementType!RoR)[] joinImpl(RoR, R)(RoR ror, R sep)
sepArr.length * (ror.length - 1);
auto result = new Unqual!RetElem[](resultLen);

size_t i = 0;
size_t j = 0;
auto first = ror.front;
result[0 .. first.length] = first[];
size_t i = first.length;
ror.popFront();
foreach(r; ror)
{
result[i .. i + sepArr.length] = sepArr[];
i += sepArr.length;
result[i .. i + r.length] = r[];
i += r.length;

if(++j < ror.length)
{
result[i .. i + sepArr.length] = sepArr[];
i += sepArr.length;
}
}

return cast(RetType)result;
Expand All @@ -1539,30 +1537,14 @@ ElementEncodingType!(ElementType!RoR)[] joinImpl(RoR, R)(RoR ror, R sep)
return typeof(return).init;

auto result = appender!(typeof(return))();

static if(isForwardRange!RoR)
{
immutable numRanges = walkLength(ror);
size_t j = 0;
}

foreach(r; ror)
result.put(ror.front);
ror.popFront();
foreach (r; ror)
{
result.put(sep);
result.put(r);

static if(isForwardRange!RoR)
{
if(++j < numRanges)
result.put(sep);
}
else
result.put(sep);
}

static if(isForwardRange!RoR)
return result.data;
else
return result.data[0 .. $ - sep.length];
return result.data;
}

ElementEncodingType!(ElementType!RoR)[] joinImpl(RoR)(RoR ror)
Expand Down

0 comments on commit 25abd87

Please sign in to comment.