Is there a difference between :
StringBuilder requete = new StringBuilder();
requete.Append(" INSERT into " + listeLibelleTable[index] + " ( ");
and
StringBuilder requete = new StringBuilder();
requete.Append(" INSERT into ");
requete.Append(listeLibelleTable[index]);
requete.Append(" ( ");
When I say "difference" I mean in terms of performance, if this code is in a loop for example.
I think these line
requete.Append(" INSERT into " + listeLibelleTable[index] + " ( ");
is resolved at compile time so It should not be any impact in terms of performance but I'm not sure of that
Unless listeLibelleTable[index] can indeed be resolved at compile time (which I greatly doubt), using the string concatenation seems to be counter productive to the use of the StringBuilder.
In your second example you are concatenating a string and then appending it instead of appending to the StringBuilder.
In either case, you should probably use AppendFormat for readability:
requete.AppendFormat(" INSERT into {0} ( ", listeLibelleTable[index]);
Your first code is performing the concatenation, building a complete string and then appending it to the StringBuilder. Assuming you're also going to append other things, the second form could be a little bit faster... it doesn't need the temporary string with the result of that part of the concatenation.
On the other hand, if you're performing a database operation, the difference is going to be immeasurably small.
I think doing this:
" INSERT into " + listeLibelleTable[index] + " ( "
you use more memory to store result of concat operation!
String concatenation will create new String object and copy exisiting value, and despose old string. show it will be slow.
check http://kaioa.com/node/59 for reference
Related
Assume we have
string one = "1";
string two = "2";
string three = "3";
And we want to get the result string
result = "1, 2, 3"
by building it from the above three variables.
I know I can do it like this
result = one + ", " + two + ", " + three;
but as far as I understand, then a lot of strings are generated and thrown away again (first 1, then 1,, then 1, 2, then 1, 2,, then 1, 2, 3). I know I can use a StringBuilder to prevent creating new strings all the time, but this is also not what I am looking for.
In my case, I know from the start how the string will look, I only need to put references of the variables into the result string.
I know I have seen a syntax before (C#). I think it looks a bit like this:
result = "{0}, {1}, {2}", one, two, three
Questions:
What is the syntax?
What is the correct name for putting a string together from pieces when the pattern is known? I assume there is a more specific word than "concatenate". In my understanding, "concatenate" is something you want to do at runtime, when you don't know in the beginning which or how many strings are to be connected.
- Is there a difference in performance or memory usage compared to using a StringBuilder? (see https://stackoverflow.com/a/299541/5333340 - it seems string.Concat is faster.)
Here is the string.Join approach. This avoids the redundant inserting of the seperator compared to your required String.Format
string one = "1";
string two = "2";
string three = "3";
string result = string.Join(", ", one, two, three);
in addition to string.join and string.format, you could also use interpolated strings which looks cleaner than string.format in many scenarios - e.g.
result = $"{one}, {two}, {three}";
What is the syntax?
var result = string.Format("{0}, {1}, {2}", one, two, three);
or (C# 6.0 string interpolation, which is just syntactic sugar for string.Format)
var result = $"{one}, {two}, {three}";
What is the correct name for putting a string together from pieces when the pattern is known? I assume there is a more specific word than "concatenate". In my understanding, "concatenate" is something you want to do at runtime, when you don't know in the beginning which or how many strings are to be connected.
String formatting or string interpolation.
Is there a difference in performance or memory usage compared to using a StringBuilder?
As of .NET 4.0, string.Format uses a cached StringBuilder internally, so the performance difference is minimal. For very large and/or very many strings, using a raw StringBuilder will be fastest, but for most cases, string.Format will be good enough in terms of performance, and a lot more readable.
The syntax you are looking for is
result = String.Format("{0}, {1}, {2}", one, two, three);
Trying to determine if it's a better practice to use string.Format in place of concatenating strings and if so, why is this? Also, are their advantages/disadvantages to one or the other that I should be aware of?
This:
string foo = "I" + " am " + " a " + " string.";
or:
string bar = string.Format("{0} am a {1}.", "I", "string");
Obviously oversimplified examples, just wanting to be clear.
The "best practice" should be the thing that makes your code the most readable and maintanable. The performance difference between concatenating strings versus using string.Format versus using a StringBuilder is so small that it's essentially irrelevant.
Assuming the first method was not optimized at compile time, because strings are immutable it will create many intermediate strings. It'll work from left to right so there will first be "I am ", then "I am a ", and finally "I am a string." which is stored in foo.
String.format will not make intermediate strings. To my understanding it does all the manipulation in a char[] which is then made immutable by being made a String.
I have string variable declared globally.I have to append a substring to this string dynamically based on the user input.To do this I use str=str+substring;
In this case the string in str doesn't have meaningful sentence finally ie.,there is no spaces between the words.to make it sense I used the following statement instead,
str=str+" "+substring; or str=str+substring+" ";
here everytime I have to append extra space to the substring before appending this to the main string were additional string processing is required.
Can anybody help on this were i can do this effectively?
It depends on how often you are doing it. If this is intermittent (or in fact pretty-much anything except a tight loop), then forget it; what you have is fine. Sure an extra string is generated occasionally (the combined substring/space), but it will be collected at generation 0; very cheap.
If you are doing this aggressively (in a loop etc), then use a StringBuilder instead:
// declaration
StringBuilder sb = new StringBuilder();
...
// composition
sb.Append(' ').Append(substring);
...
// obtaining the string
string s = sb.ToString();
A final (unrelated) point - re "globally" - if you mean static, you might want to synchronize access if you have multiple threads.
What do you want to achieve exactly? You could store the words in a list
List<string> words = new List<string>();
...
words.Add(str);
And then delay the string manipulation (i.e. adding the spaces between words) until at the very end. This way, you're on the fly operation is just an add to a list, and you can do all the complex processing (whatever it may be) at the end.
If you are doing it rarely, you could slightly pretty up the code by doing:
str += " " + substring;
Otherwise, I'd go with Nanda's solution.
#Nanda: in your case you should use string builder.
StringBuilder data = new StringBuilder();
data.AppendFormat(" {0}", substring);
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How should I concatenate strings?
There are several ways to concat strings in everyday tasks when performance is not important.
result = a + ":" + b
result = string.Concat(a, ":", c)
result = string.Format("{0}:{1}", a, b);
StringBuilder approach
... ?
what do you prefer and why if efficiency doesn't matter but you want to keep the code most readable for your taste?
It depends on the use. When you just want to concat two strings, using a + b is just much more readable than string.Format("{0}{1}", a, b). However, it is getting more complex, I prefer using string.Format. Compare this:
string x = string.Format("-{0}- ({1})", a, b);
against:
string x = "-" + a + "- (" + b + ")";
I think that in most cases it is very easy to spot the most readable way to do things. In the cases where it is debatable which one is more readable, just pick one, because your boss isn't paying for these pointless discussions ;-)
string.Format for me, but in practice I use whichever is fit for purpose, taking into account performance and readability.
If it was two variables I'd use.
string.Concat(str1, str2);
If it contained a constant or something that requires formatting then.
string.Format("{0} + {1} = {2}", x, y, x + y);
Or for something like an SQL query
string SqlQuery = "SELECT col1, col2, col3, col4" +
"FROM table t " +
"WHERE col1 = 1";
And string builder when performance matters.
String.Format(...) is slowest.
For simple concatenations which don't take place in a loop, use String.Concat(...) or the + operator, which translate to the same under the hood, afaik. What is more readable is very subjective.
Using a StringBuilder for simple concatenations is over-the-top for simple concatenations as well and has most likely too much overhead. I'd only use it in a loop.
For something like this (which I'm guessing is being sent to the UI), I would definitely prefer String.Format. It allows the string to be internationalized easy; you can grep for calls to String.Format and replace them with your translating format.
My personal preference is:
I find the + approach the most readable and only use Format() or a StringBuilder if there is a good reason (i18n, performance etc) for it. I (almost) never use Concat.
I think I find the + approach easier to read than Format() simply because I don't have to skip ahead to the end to see what variables are put into in the {} place-holders. And if the place-holders aren't in numeric order, it gets even harder to read imo.
But I guess for larger projects it makes sense to simply enforce using Format by a style guide just in case the code might be (re-)used in a project requiring i18n later on.
string.Format
for few concats. for more I use
StringBuilder approach
even if performance is not important. there is a team agreement I have to follow
I prefer String.Format for small strings, and StringBuilder for larger ones. My main reason is readability. It's a lot more readable to me to use String.Format (or StringBuilder.AppendFormat()), but I have to admit that that is just personal preference.
For really big text generation, you might want to consider using the new (VS2010) T4 Preprocessed Templates - they are really nice.
Also, if you're ever in VB.NET, I like the XML literal technique Kathleen Dollard talked about in episode 152 of hanselminutes.
Prefer to use:
String.Concat for simple concatenations like String.Concat("foo", bar);
String.Format for complex formatting like String.Format("{1}", url, text);
StringBuilder for massive concatenations like:
var sb = new StringBuilder();
sb.AppendLine("function fooBar() {");
sp.AppendLine(String.Join(Environment.NewLine, blah));
sp.AppendLine("}");
page.RegisterClientScript(page.GetType(), sb.ToString());
Prefer to avoid "foo" + "bar" (as well as if (foo == "bar"). And especially String.Format("{0}{1}", foo, bar) and
throw new Exception("This code was" +
"written by developer with" +
"13\" monitor");
My static method returns the following concatenated string like this
return (Sb.ToString() + " " + ds.Tables[1].Rows[0].ItemArray[0].ToString() + " " + ds.Tables[2].Rows[0].ItemArray[0].ToString());
Is this a good/bad practise or should i use stringbuilder for it....
String concatenation in a single shot will be faster than using a StringBuilder - although if Sb is already a StringBuilder, it might make sense to append to that instead (assuming it's a local variable). Assuming this is actually data which has come from a database, the time taken to fetch it is going to vastly exceed the string concatenation here anyway.
Note that you don't need all these calls to ToString() - this would do just as well:
return (Sb + " " + ds.Tables[1].Rows[0].ItemArray[0] + " " +
ds.Tables[2].Rows[0].ItemArray[0]);
Here's the equivalent using the existing builder:
return Sb.Append(" ")
.Append(ds.Tables[1].Rows[0].ItemArray[0])
.Append(" ")
.Append(ds.Tables[2].Rows[0].ItemArray[0])
.ToString();
This might be slightly faster - it will depend on various things. Personally I'd probably use the concatenation version anyway, as it's slightly simpler IMO. I highly doubt that you'd see much difference in performance. Note that this is a bit of a special case, as you've already got a StringBuilder; in the general case of concatenating a set of items where they can all be specified in one compile-time expression, concatenation can be faster as a single method call can provide all the required information.
I have a page on StringBuilder vs string concatenation if you want more details and guidelines.
I think this is more readable:
return String.Format("{0} {1} {2}",
Sb,
ds.Tables[1].Rows[0].ItemArray[0],
ds.Tables[2].Rows[0].ItemArray[0]);
About concatenating strings or using StringBuilder:
Concatenating Strings Efficiently
StringBuilder and String Concatenation
If you're calling this in a tight loop, you'll be probably be better off using StringBuilder (but this piece should be profiled nevertheless). Otherwise, concatenation is perfectly fine. I would change it, however, to String.Format() for maintainability/readability reasons.