I have a string1, string2,...,stringn
and values of each strings are
string1 = "s1k1-s1k2-s1k3-....-s1kn | s1v1-s1v2-s1v3-....-s1vn";
string2 = "s2k1-s2k2-s2k3-....-s2kn | s2v1-s2v2-s2v3-....-s2vn";
.............
stringn = "snk1-snk2-snk3-....-snkn | snv1-snv2-snv3-....-snvn";
Now, I want to populate the Dictionary<string, string>() with the key and values as follows.
var dict = new Dictionary<string, string>();
dict.Add(s1k1, s1v1);
dict.Add(s1k2, s1v2);
:
:
dict.Add(snkn, snvn);
Below is my sample code:
string string1 = "s1k1-s1k2-s1k3-s1kn|s1v1-s1v2-s1v3-s1vn";
string string2 = "s2k1-s2k2-s2k3-s2kn|s2v1-s2v2-s2v3-s2vn";
string stringn = "snk1-snk2-snk3-snkn|snv1-snv2-snv3-snvn";
var dict = new Dictionary<string, string>();
new List<string> { string1, string2, stringn }.ForEach(str =>
{
var strSplit = str.Split('|');
var strKeys = strSplit[0].Split('-');
var strValues = strSplit[1].Split('-');
strKeys.Zip(strValues, (key, value) => new { key, value }).ToList().ForEach(filed => dict.Add(filed.key, filed.value));
});
Is it possible to optimize this code ?
To my mind the most costly operation here in terms of memory usage is
strSplit = str.Split('|'). It creates two large strings that go directly to a garbage afterstrKeysandstrValuesare obtained. Later all these garbage strings will be collected by garbage collector which will negatively affect the performance.The
strKeysandstrValuesstring arrays contain strings that will be used indict, so the memory loss here is minimal.To optimize memory usage you’ll have to traverse
strchar-by-char and create keys and values usingStringBuilderclass. In this case memory loss will be minimal, however your code won’t be as clean as it is now. So I would recommend such solution only if this part of the code is the real performance bottleneck in your application.