我在下面有这个代码,我循环遍历字符串,并通过char比较所有char,这是非常慢的过程,我想知道如何改进这段代码.
//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;
Run Code Online (Sandbox Code Playgroud)
这太棒了.
我改变了以下两行,并获得了惊人的性能提升,如1000%或其他
首先改变这个
string ch = googlejson.Substring(x, 1);
Run Code Online (Sandbox Code Playgroud)
那个
string ch = googlejson[x].ToString();
Run Code Online (Sandbox Code Playgroud)
其次,我用String Builder替换了所有+ = ch
output.Append(ch);
Run Code Online (Sandbox Code Playgroud)
因此,这两项变更会对性能产生最大影响
首先,Substring当只处理单个字符时,不应该使用s.使用
char ch = googlejson[x];
Run Code Online (Sandbox Code Playgroud)
代替.
您还可以考虑使用a StringBuilder作为output变量.如果你正在使用字符串,你应该总是记住,字符串在.NET中是不可变的,所以对于每一个
output += ch;
Run Code Online (Sandbox Code Playgroud)
创建了一个新的字符串实例.
使用
StringBuilder output = new StringBuilder();
Run Code Online (Sandbox Code Playgroud)
和
output.append(ch);
Run Code Online (Sandbox Code Playgroud)
代替.