Home > c# > stringbuilder vs string.concat

stringbuilder vs string.concat

June 11Hits:5
Advertisement

I was reading the following article about StringBuilder vs string.concat: http://jonskeet.uk/csharp/stringbuilder.html

And couldn't figure out which one would be better in the following situation:

StringBuilder address = new StringBuilder();  address.Append(retailer.Street.Replace(",", "<br>").Replace("\n", "<br>")); address.Append("<br>");  if (!string.IsNullOrWhiteSpace(retailer.City))  {   address.Append(retailer.City);   address.Append("<br>"); }  if (!string.IsNullOrWhiteSpace(retailer.County))  {   address.Append(retailer.County);   address.Append("<br>"); }  address.Append(retailer.Postcode);  return MvcHtmlString.Create(address.ToString()); 

According to the article, as it is not in a loop, I should be using string.Concat, but as there are if statements while building the string, I was wondering if that still applied. Or would I be better off doing the following:

string address = string.Concat(retailer.Street.Replace(",", "<br>").Replace("\n", "<br>"), "<br>");  if (!string.IsNullOrWhiteSpace(retailer.City)) {     address += string.Concat(retailer.City, "<br>"); }  if (!string.IsNullOrWhiteSpace(retailer.County)) {     address += string.Concat(retailer.County, "<br>"); }  address += retailer.Postcode;  return MvcHtmlString.Create(address); 

Answers

DISCLAIMER: You haven't properly defined "better" so I'll assume you're talking about performance

You're fixing the wrong problem.

Under the assumption that your retailer is an instance of some Retailer POCO, you should properly normalize your data and extract the Address data into a separate Table / POCO.

Then you can stop generating HTML in some Controller code and instead do something like:

retailer.Address.ToHTMLString();

This is significantly cleaner and allows central modification of "ToHTML" rules.

In addition to that I don't think you actually have to care about the performance difference between these two. Have you profiled your code and proved that this is the bottleneck? If it isn't.... It's good enough I'd say.
You seem to be falling prey to the problems described in Eric Lippert's Performance Rant

Vogel612 has already covered the performance aspect. I'd like to make a suggestion that will definitely be slower but has an elegance to it:

var addressParts = new[] {
    retailer.Street.Replace(",", "<br>").Replace("\n", "<br>"),
    retailer.City,
    retailer.County,
    retailer.Postcode
};
var nonEmptyAddressParts = addressParts.Where(p => !string.IsNullOrEmpty(p));
var htmlAddress = string.Join("<br>", nonEmptyAddressParts);

You then sidestep your entire Concat vs StringBuilder dilemma.

Tags:strings

Related Articles

  • stringbuilder vs string.concatJune 11

    I was reading the following article about StringBuilder vs string.concat: http://jonskeet.uk/csharp/stringbuilder.html And couldn't figure out which one would be better in the following situation: StringBuilder address = new StringBuilder(); address.

  • StringBuilder vs String concatenation in toString() in JavaOctober 7

    Given the 2 toString() implementations below, which one is prefered: public String toString(){ return "{a:"+ a + ", b:" + b + ", c: " + c +"}"; } or public String toString(){ StringBuilder sb = new StringBuilder(100

  • String concat vs string format in Apex?December 10

    I believe there is a performance benefit for using string format in languages like .NET and Java over concatenating strings. Is this also the case for Apex and force.com ? string s = 'this'+'is'+'a'+'concatenation'; vs string s = string.format('{0}{1

  • Assembling a user agent descriptor, implemented using StringBuilder vs StringJanuary 18

    I think performance won't be a big issue here as the concatenation only happens once (2-3 at worse because of multiple threads). Out of the two methods, which one would you prefer, in terms of readability and performance? Is there any better way to a

  • What is the use of the return value of the StringBuilder Append(string-) function?February 15

    The complete syntax of StringBuilder's Append(string s) function (and similar functions) is StringBuilder myStringBuilder.Append(string myString) since myStringBuilder.Append(string myString) already adds the string to myStringBuilder, I was wonderin

  • Optimizing jQuery table building by replacing appends with string concatJune 16

    I've wrote some code to create a grid of data, however depending on the size of the grid being drawn, IE8 shows a warning message about a long running script. I've read that multiple appends are a slow way of drawing a table, so I'm trying to concate

  • Issue in string concation in SQLFebruary 3

    i am concatenate string with int variable to string in sql for that i have write Declare @convertname nvarchar(200) Declare @i int Declare @iValueConvertToString nvarchar(200) Declare @tempSename nvarchar(200) Declare @checkname int; SET @i = 0 While

  • How to write efficient javascript/jQuery code involving loops and string concat?January 30

    I am using kendo grid's onDataBound event to do something. Here's my jQuery code: console.time('withoutnot'); jQuery(e.sender.dataSource._data).each(function (i, v) { if (v.IsReadonly) { e.sender.wrapper.find("tr[data-uid='" + v.uid + "'] .

  • Java implementation of spell-checking algorithmMay 4

    This little program was written for an assignment in a data structures and algorithms class. I'll just note the basic requirements: Given an inputted string, the program should check to see if it exists in a dictionary of correctly spelled words. If

  • Concat two strings when initialising class object without providing the concatenated stringJanuary 19

    How can i initialise the FullName variable to auto concat the previous two strings? Due to system design and constraints I can't pass the concatenated string when initialising, so is there a way to initialise the FullName variable without providing t

  • Best practice / alternatives for string manipulation with an emphasis on readabilitySeptember 11

    As a personal habit I generally prefer to use string replace and format methods, along with string "patterns", in lieu of string concatenation and other methods in most languages I use (typically C# and Javascript). For example, if I want to gen

  • Random string generationNovember 12

    I'm using this C# function to generate random coupons for a system. How can I improve it? public static string GenerateCoupon(int length) { string result = string.Empty; Random random = new Random((int)DateTime.Now.Ticks); List<string> characters =

  • LINQ approach to flatten Dictionary to stringFebruary 15

    I have a Dictionary<string,string> and want to flatten it out with this pattern: {key}={value}|{key}={value}|{key}={value}| I tried with a LINQ approach at first but couldn't solve it, so I ended up writing an extension method like this: public stat

  • Cleanest way to place values into stringsNovember 6

    I am trying to standardize the way I write code. Which is the best way to place the values into a string, method 1 or 2? string myCat = "persian"; // Method 1 Console.WriteLine("I have a wild {0} cat that likes to visit", myCat); // Me

  • Given a string, return a string where every character in the original is doubledMay 22

    For example, given the string "xyz", return the string "xxyyzz". I was given this as a part of a test. I would really appreciate if you can help me to find a better way of doing it. I came up with two methods to do the same thing but o

  • Effectiveness of masking a stringOctober 28

    The assignment is to mask (or rather unmask) certain indexes from a string. Both the input string and the demasker are strings. An example shows how it's supposed to work. Input: "abcdefgh" Mask: "2-4,6" Output: "bcdf" The in

  • Join strings from a List string while also formating themNovember 28

    The code I have wrote works fine, this inquiry being purely for educational purposes. I want to know how others would do this better and cleaner. I especially hate the way I add the list items to another list before they are joined. There has to be a

  • String reverse and pairing reversed wordsDecember 13

    These are questions from an interview: Reverse a string Find matching anagrams in a word list using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public c

  • Should I use .ToString() when concatenating string and integer variables in C#?December 13

    int a = 1; int b = 2; int sum = a + b; string expression = "Expression: " + a + " + " + b + " = " + sum; Console.WriteLine(expression); //displays Expression 1 + 2 = 3 Should I use: string expression = "Expression: "

  • Converting strings to PascalCaseDecember 3

    I have a method which I use on occasion to convert strings (like enum and property names) to PascalCase for display. It's fairly simple, so there's probably not much to comment on, but as usual I appreciate any advice on improving it. /// <summary>

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.458 s.