473,466 Members | 1,646 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Log strings...

I do some logging like so:

Log.Error("The song was not found. Artist - " + artist + ", Title - " +
title + "\n" + exception.ToString());

Now I know that building strings in that way is innefficient, but using
the String builder seems too complicated for the taks.

StringBuilder b = new StringBuilder();
b.Append("The song was not found. Artist - ");
b.Append(artist);
b.Append(", Title - ");
b.Append(title);
b.Append("\n");
b.Append(exception.ToString());

Log.Error(b.ToString());

Yea this should be more efficient, but looking at this mess there just
*has* to be a better way, so what is it?

Thanks,
Nick Z.
Nov 17 '05 #1
10 1462
Nick,

Actually, this will be pretty quick. This compiles down to a call to
Concat. Concat will cycle through the strings, calculating the final length
of the string. Then, it will copy the strings over to the new string. It
might actually beat out StringBuilder in this case (since StringBuilder
would overallocate). Not by much (probably).

For single concatenations, Concat (or +) is the way to go. For things
in a loop where you will be appending to the previous result, StringBuilder
is better.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Nick Z." <pa*****@gmail.com> wrote in message
news:Vn*****************@fe08.lga...
I do some logging like so:

Log.Error("The song was not found. Artist - " + artist + ", Title - " +
title + "\n" + exception.ToString());

Now I know that building strings in that way is innefficient, but using
the String builder seems too complicated for the taks.

StringBuilder b = new StringBuilder();
b.Append("The song was not found. Artist - ");
b.Append(artist);
b.Append(", Title - ");
b.Append(title);
b.Append("\n");
b.Append(exception.ToString());

Log.Error(b.ToString());

Yea this should be more efficient, but looking at this mess there just
*has* to be a better way, so what is it?

Thanks,
Nick Z.

Nov 17 '05 #2
Ah, now it all makes sense, thanks.
I knew the compiler has to be smarter than doing this one string at a
time, but everybody keeps saying, use StringBuilder, thats where the
confusion started.

Thanks again.
Nick Z.

Nicholas Paldino [.NET/C# MVP] wrote:
Nick,

Actually, this will be pretty quick. This compiles down to a call to
Concat. Concat will cycle through the strings, calculating the final length
of the string. Then, it will copy the strings over to the new string. It
might actually beat out StringBuilder in this case (since StringBuilder
would overallocate). Not by much (probably).

For single concatenations, Concat (or +) is the way to go. For things
in a loop where you will be appending to the previous result, StringBuilder
is better.

Hope this helps.

Nov 17 '05 #3
Nick,

Yes, there typically tends to be confusion in this area.

Basically, for one shot operations, where the outcome is not a factor in
the next concatenation operation, the Concat/+ route is the best way to go.
For example:

// Add N strings together
public void Write(string str1, string str2, string str3)
{
Console.Writeline(str1 + str2 + str3);
}

When you are in a tight loop, and you are using the result of the
concatenation for the next operation (say you are concatenating values from
a dataset), then the string builder is better. For example:

// Get a comma delimited list of the "value" column in the dataset.
public string CommaDelimitedString(DataTable table)
{
// The result.
StringBuilder result = new StringBuilder();

// Enumerate through the table.
foreach (DataRow row in table)
{
// Append the value, and a comma.
result.AppendFormat("{0},", row["value"]);
}

// Remove the last comma, if there are items in the builder.
if (result.Length > 0)
{
// Remove the last comma.
result.Remove(result.Length - 1, 1);
}

// Return the result.
return result.ToString();
}
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Nick Z." <pa*****@gmail.com> wrote in message
news:AC****************@fe08.lga...
Ah, now it all makes sense, thanks.
I knew the compiler has to be smarter than doing this one string at a
time, but everybody keeps saying, use StringBuilder, thats where the
confusion started.

Thanks again.
Nick Z.

Nicholas Paldino [.NET/C# MVP] wrote:
Nick,

Actually, this will be pretty quick. This compiles down to a call to
Concat. Concat will cycle through the strings, calculating the final
length of the string. Then, it will copy the strings over to the new
string. It might actually beat out StringBuilder in this case (since
StringBuilder would overallocate). Not by much (probably).

For single concatenations, Concat (or +) is the way to go. For
things in a loop where you will be appending to the previous result,
StringBuilder is better.

Hope this helps.

Nov 17 '05 #4

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:OO**************@TK2MSFTNGP10.phx.gbl...
Nick,

Yes, there typically tends to be confusion in this area.

Basically, for one shot operations, where the outcome is not a factor
in the next concatenation operation, the Concat/+ route is the best way to
go. For example:

// Add N strings together
public void Write(string str1, string str2, string str3)
{
Console.Writeline(str1 + str2 + str3);
}

When you are in a tight loop, and you are using the result of the
concatenation for the next operation (say you are concatenating values
from a dataset), then the string builder is better.


Another way to say this is, when the compiler can optimize the String
concatenation, it will.
Nov 17 '05 #5
Mike,

Well, not completely. The key here is knowing what the compiler will
do. If you simply use concatenation in the case where you are concatenating
strings for the comma delimited string, you will end up doing way more than
you should.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eX*************@TK2MSFTNGP10.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:OO**************@TK2MSFTNGP10.phx.gbl...
Nick,

Yes, there typically tends to be confusion in this area.

Basically, for one shot operations, where the outcome is not a factor
in the next concatenation operation, the Concat/+ route is the best way
to go. For example:

// Add N strings together
public void Write(string str1, string str2, string str3)
{
Console.Writeline(str1 + str2 + str3);
}

When you are in a tight loop, and you are using the result of the
concatenation for the next operation (say you are concatenating values
from a dataset), then the string builder is better.


Another way to say this is, when the compiler can optimize the String
concatenation, it will.

Nov 17 '05 #6
not too sure about efficiency but for simplifying usage you might try
String.Format()

e.g.

String artist = "Matchbox 20";
String title = "busted";
String exceptionMessage = "Arfle, barfle, gloop";

const String FMT_MSG = "The Song was not found. Artist:
{0}, Title: {1}.\nException: {2}";
MessageBox.Show(String.Format(FMT_MSG,
artist,
title,
exceptionMessage));

hth,
Alan.

Nov 17 '05 #7
Nick Z. <pa*****@gmail.com> wrote:
I do some logging like so:

Log.Error("The song was not found. Artist - " + artist + ", Title - " +
title + "\n" + exception.ToString());

Now I know that building strings in that way is innefficient, but using
the String builder seems too complicated for the taks.

StringBuilder b = new StringBuilder();
b.Append("The song was not found. Artist - ");
b.Append(artist);
b.Append(", Title - ");
b.Append(title);
b.Append("\n");
b.Append(exception.ToString());

Log.Error(b.ToString());

Yea this should be more efficient, but looking at this mess there just
*has* to be a better way, so what is it?


See http://www.pobox.com/~skeet/csharp/stringbuilder.html

Your first way of working is actually more efficient than the second.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
Nick Z. <pa*****@gmail.com> wrote:
Ah, now it all makes sense, thanks.
I knew the compiler has to be smarter than doing this one string at a
time, but everybody keeps saying, use StringBuilder, thats where the
confusion started.


Yes, it's one of those generalisations (like "exceptions are
expensive") which is repeated without any real consideration :(

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
Thanks for the article.
Nick Z.

Jon Skeet [C# MVP] wrote:
Nick Z. <pa*****@gmail.com> wrote:
I do some logging like so:

Log.Error("The song was not found. Artist - " + artist + ", Title - " +
title + "\n" + exception.ToString());

Now I know that building strings in that way is innefficient, but using
the String builder seems too complicated for the taks.

StringBuilder b = new StringBuilder();
b.Append("The song was not found. Artist - ");
b.Append(artist);
b.Append(", Title - ");
b.Append(title);
b.Append("\n");
b.Append(exception.ToString());

Log.Error(b.ToString());

Yea this should be more efficient, but looking at this mess there just
*has* to be a better way, so what is it?

See http://www.pobox.com/~skeet/csharp/stringbuilder.html

Your first way of working is actually more efficient than the second.

Nov 17 '05 #10

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:eE**************@TK2MSFTNGP14.phx.gbl...

Because that's in a loop, and the compiler can't see all the strings at
once, therefore can't optimize things.
Mike,

Well, not completely. The key here is knowing what the compiler will
do. If you simply use concatenation in the case where you are
concatenating strings for the comma delimited string, you will end up
doing way more than you should. "Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eX*************@TK2MSFTNGP10.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:OO**************@TK2MSFTNGP10.phx.gbl...
Nick,

Yes, there typically tends to be confusion in this area.

Basically, for one shot operations, where the outcome is not a factor
in the next concatenation operation, the Concat/+ route is the best way
to go. For example:

// Add N strings together
public void Write(string str1, string str2, string str3)
{
Console.Writeline(str1 + str2 + str3);
}

When you are in a tight loop, and you are using the result of the
concatenation for the next operation (say you are concatenating values
from a dataset), then the string builder is better.


Another way to say this is, when the compiler can optimize the String
concatenation, it will.


Nov 17 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
by: Ravi | last post by:
Hi, I have about 200GB of data that I need to go through and extract the common first part of a line. Something like this. >>>a = "abcdefghijklmnopqrstuvwxyz" >>>b = "abcdefghijklmnopBHLHT"...
17
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently...
16
by: Paul Prescod | last post by:
I skimmed the tutorial and something alarmed me. "Strings are a powerful data type in Prothon. Unlike many languages, they can be of unlimited size (constrained only by memory size) and can hold...
4
by: agent349 | last post by:
First off, I know arrays can't be compared directly (ie: if (arrary1 == array2)). However, I've been trying to compare two arrays using pointers with no success. Basically, I want to take three...
25
by: Rainmaker | last post by:
Hi, Can anyone tell me an efficient algorithm to sort an array of strings? Keep in mind that this array is HUGE and so the algorithm should me efficient enough to deal with it. Thanks
6
by: Broeisi | last post by:
Hello, I wrote the tiny progam below just to understand arrays and strings better. I have 2 questions about arrays and strings in C. 1. Why is it that when you want to assign a string to an...
2
by: Potiuper | last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C? Given: code is written in ANSI C; I know the exact nature of the strings to be...
19
by: pkirk25 | last post by:
I wonder if anyone has time to write a small example program based on this data or to critique my own effort? A file called Realm List.html contains the following data: Bladefist-Horde...
95
by: hstagni | last post by:
Where can I find a library to created text-based windows applications? Im looking for a library that can make windows and buttons inside console.. Many old apps were make like this, i guess ...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.