title: C# loop through array of chars not efficient
body: <p>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.</p>
  
  <pre><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 ) . '&lt;br&gt;';
          bool instring = false;
          bool inescape = false;
          string lastchar = "";
          string output = "";
          for ( int x=0; x&lt; googlejson.Length; x++ ) {
  
              string ch = googlejson.Substring(x, 1);
  
              //toss unnecessary whitespace
              if ( !instring &amp;&amp; ( 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;
  </code></pre>
  
  <p>This is just amazing.</p>
  
  <p>I have changed 2 following lines and gain phenomenal performance increase like 1000% or something</p>
  
  <p>First change this</p>
  
  <pre><code>string ch = googlejson.Substring(x, 1);
  </code></pre>
  
  <p>to that</p>
  
  <pre><code>string ch = googlejson[x].ToString();
  </code></pre>
  
  <p>Second I replaced all += ch with String Builder</p>
  
  <pre><code>output.Append(ch);
  </code></pre>
  
  <p>So those 2 changes had maximum performance impact.</p>