How often have you been told to use StringBuilder to concatenate strings in .NET? My guess is often enough. Here is something you may not know about string concatenation: StringBuilder is not always faster. There are already many articles out there that explain the why’s, I am not going to do that here. But I do have some test data for you.
This block of code took 1484 milliseconds to run on my PC:
for (int i = 0; i <= 1000000; i++) { // Concat strings 3 times using StringBuilder StringBuilder s = new StringBuilder(); s.Append(i.ToString()); s.Append(i.ToString()); s.Append(i.ToString()); }
And this one, using traditional concatenation, took slightly less time (1344 milliseconds):
for (int i = 0; i <= 1000000; i++) { // Concat strings 3 times using traditional concatenation string s = i.ToString(); s = s + i.ToString(); s = s + i.ToString(); }
The above data suggests that StringBuilder only starts to work faster once the number of concatenations exceed 3.
When building a large string from several string literals (such as building a SQL block, or a client side javascript block), use neither traditional concatenation nor StringBuilder. Instead, choose one of the methods below:
// Build script block string s = "<script>" + "function test() {" + " alert('this is a test');" + " return 0;" + "}";
The compiler concatenates that at compile time. At run-time, that works as fast as a big string literal.
I sometimes use the @ string literal which allows for newlines (I find this syntax is harder to maintain, formatting-wise, than using the + operator):
string s = @"<script> function test() { alert('this is a test'); return 0; }";
Both methods above run about 40 times faster than using StringBuilder or traditional string concatenation.
I have posted a follow-up article to provide more detailed analysis and to answer some of the questions asked by readers.
To list available contexts: kubectl config get-contexts To show the current context: kubectl config current-context…
kubectl exec -it <podname> -- sh To get a list of running pods in the…
# Create a soft symbolic link from /mnt/original (file or folder) to ~/link ln -s…
git config --global user.name "<your name>" git config --global user.email "<youremail@somewhere.com>" Related Commands Show current…
TypeScript/JavaScript function getLastMonday(d: Date) { let d1 = new Date(d.getFullYear(), d.getMonth() + 1, 0); let…
I had to do some SMTP relay troubleshooting and it wasn't obvious how to view…
View Comments