HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Generating 2 comma-separated lists from list of key value pairs

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
commavalueseparatedgeneratinglistslistfrompairskey

Problem

Could this code:

var a = new StringBuilder();
var b = new StringBuilder();
var kvps = new List>
{
    new KeyValuePair(Guid.NewGuid(), 1),
    new KeyValuePair(Guid.NewGuid(), "hello")
};
for (var c = 0; c = kvps.Count - 1) continue;
    a.Append(",");
    b.Append(",");
}


be improved in terms of performance to achieve this:

a = e1b7978c-127f-4a5f-a17b-737e03484172,cbbd1573-950c-4ca4-94b7-72a08b4a61d0
b = 1,hello

Solution

Performance here will only matter if the input List is large. There are two things that can be done to make the output loop faster:

-
initialize the starting capacity of the StringBuilder to match your expectations of what size it will need to be.

In this case, you know the GUUID's are 36 characters long, with a comma, makes it 37. You should initialize that StringBuilder to ... new StringBuilder(37 * kvps.Count);. Similarly, if you have an approximate size of the average length for the other Stringbuilder, then double-it, and use it as the initial capacity constructor.

-
If the loop happens (very) often, you can get a very slight performance improvement by doing the following (removing the if condition from inside the loop):

foreach (KeyValuePair kv in kvps)
{
    a.Append(kv.Key);
    a.Append(",");
    b.Append(kv.Value);
    b.Append(",");
}
// remove the trailing comma.
if (kvps.Count > 0) {
    a.Length = a.Length - 1;
    b.Length = b.Length - 1;
}


It should go without saying that the names a and b are bad names for the StringBuilder instances ....

Code Snippets

foreach (KeyValuePair kv in kvps)
{
    a.Append(kv.Key);
    a.Append(",");
    b.Append(kv.Value);
    b.Append(",");
}
// remove the trailing comma.
if (kvps.Count > 0) {
    a.Length = a.Length - 1;
    b.Length = b.Length - 1;
}

Context

StackExchange Code Review Q#55220, answer score: 10

Revisions (0)

No revisions yet.