c# - Foreach loop - performance with long string -
i'm facing problem performance in c# application. problem quite long string - base64 coded, not ordinary. characters has moved 5 characters , odd ones 5 characters down, create readable base64 string. heres code:
string b64stock; // <- long 1 int b = 0; string b64readable = ""; foreach (char c in b64stock) { if ((b % 2) == 0) { int asciichar = (int)c; asciichar += 5; b64readable += (char)asciichar; } else { int asciichar = (int)c; asciichar -= 5; b64readable += (char)asciichar; } b++; }
i checked code stopwatch. takes 17 seconds, execute loop. steps should take, make more efficient ?
use stringbuilder
rather string:
string b64stock; // <- long 1 int b = 0; stringbuilder sb = new stringbuilder(b64stock.length); foreach (char c in b64stock) { int asciichar = (int)c; if ((b % 2) == 0) { asciichar += 5; } else { asciichar -= 5; } sb.append((char)asciichar); b++; } string b64readable = sb.tostring();
the performance problem you're experiencing because strings immutable. when write mystring += 'x'
, doesn't modify mystring
. rather, creates new string of required length , copies old mystring
it. kills performance relatively short strings.
the stringbuilder
works expected string to. calling append
adds character buffer, , buffer expanded automatically needed. although in case it's not expanded @ because pre-allocated required length.
Comments
Post a Comment