I have this specific code:
public static string To_Bits(string data, object ConversionTable)
{
string toBits = "";
string tmpBin = "";
var json = JsonConvert.SerializeObject(ConversionTable);
var cTable = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
for (int i=0; i<data.Count(); i )
{
tmpBin = data[i].ToString();
toBits = cTable[tmpBin];
}
return toBits;
}
As the data gets larger, the conversion based on the conversionTable
takes longer, and in some instances VS 2019 gives me the following message "The application is in break mode".
Is their a way to optimize this code to have it process faster, via LINQ or another method?
CodePudding user response:
There are two slow moments:
data.Count()
- it is calculating length of string on each loop iterationtoBits =
better to useStringBuilder
to avoid unnecessary allocations
public static string To_Bits(string data, object ConversionTable)
{
var toBits = new StringBuilder();
var tmpBin = "";
var json = JsonConvert.SerializeObject(ConversionTable);
var cTable = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
for (int i = 0; i < data.Length; i )
{
tmpBin = data[i].ToString();
toBits.Append(cTable[tmpBin]);
}
return toBits.ToString();
}
CodePudding user response:
try replacing
for (int i=0; i<data.Count(); i )
{
tmpBin = data[i].ToString();
toBits = cTable[tmpBin];
}
with
foreach (string c in data)
{
toBits = cTable[c];
}