I have this code below where I loop through string and compare everything char by char and it's very slow process I wonder how I can improve this code.
//delete anti-xss junk ")]}'\n" (5 chars);
if (trim)
{
googlejson = googlejson.Substring(5);
}
//pass through result and turn empty elements into nulls
//echo strlen( $googlejson ) . '<br>';
bool instring = false;
bool inescape = false;
string lastchar = "";
string output = "";
for ( int x=0; x< googlejson.Length; x++ ) {
string ch = googlejson.Substring(x, 1);
//toss unnecessary whitespace
if ( !instring && ( Regex.IsMatch(ch, @"/\s/"))) {
continue;
}
//handle strings
if ( instring ) {
if (inescape) {
output += ch;
inescape = false;
} else if ( ch == "\\" ) {
output += ch;
inescape = true;
} else if ( ch == "\"") {
output += ch;
instring = false;
} else {
output += ch;
}
lastchar = ch;
continue;
}
switch ( ch ) {
case "\"":
output += ch;
instring = true;
break;
case ",":
if ( lastchar == "," || lastchar == "[" || lastchar == "{" ) {
output += "null";
}
output += ch;
break;
case "]":
case "}":
if ( lastchar == "," ) {
output += "null";
}
output += ch;
break;
default:
output += ch;
break;
}
lastchar = ch;
}
return output;
This is just amazing.
I have changed 2 following lines and gain phenomenal performance increase like 1000% or something
First change this
string ch = googlejson.Substring(x, 1);
to that
string ch = googlejson[x].ToString();
Second I replaced all += ch with String Builder
output.Append(ch);
So those 2 changes had maximum performance impact.
googlejson.Substring(x, 1)For loop, I think it is slow not because the code is not efficient but because the code is complicate. Without consider of improving your method (as I don't know your requirement), if you are worried about long non-responding times of the UI, I suggest you to put the function in a backgroundworker and implement a progressbar if you haven't done so already.