String Concatenation - Best Approach?

R

Ranjith

private string ConcatenateStrings(i1, i2, i3)
{
string result = "a"+function1(i1)+"b"+function2(i2)+"c"+function3
(i3);
return result;
}

What among the below three approaches is the best?
1. using + operator
2. using string.concat
3. using stringbuilder

The function is called around 10000 times
 
B

Bjørn Brox

Ranjith skrev:
private string ConcatenateStrings(i1, i2, i3)
{
string result = "a"+function1(i1)+"b"+function2(i2)+"c"+function3
(i3);
return result;
}

What among the below three approaches is the best?
1. using + operator
2. using string.concat
3. using stringbuilder

The function is called around 10000 times

Usually stringbuilder is the fastest method, but since you are using
only one statement concat would also work well.

Anyhow: Skip the extra ConcatenateStrings() level
 
D

Dawid Rutyna

What among the below three approaches is the best?
1. using + operator
2. using string.concat
3. using stringbuilder

I understand that best means the fastest. I was unable to answer so I wrote
simple .Net application, look at the results.

private const string _content = @"Query notifications were introduced in SQL
Server 2005 and SQL Server Native Client. Built upon the Service Broker
infrastructure introduced in SQL Server 2005, query notifications allow
applications to be notified when data has changed. This feature is
particularly useful for applications that provide a cache of information
from a database, such as a Web application, and need to be notified when the
source data is changed.
Query notifications allow you to request notification within a specified
time-out period when the underlying data of a query changes. The request for
notification specifies the notification options, which include the service
name, message text, and time-out value to the server. Notifications are
delivered through a Service Broker queue that applications may poll for
available notifications.
The syntax of the query notifications options string is:
service=<service-name>[;(local database=<database> | broker instance=<broker
instance>)]
For example:
service=mySSBService;local database=mydb
Notification subscriptions outlive the process that initiates them, as an
application may create a notification subscription and then terminate. The
subscription remains valid, and the notification will occur if the data
changes within the time-out period specified when the subscription was
created. A notification is identified by the query executed, the
notification options, and the message text, and may be cancelled by setting
its time-out value to zero.
Notifications are sent only once. For continuous notification of data
change, a new subscription must be created by re-executing the query after
each notification is processed.
SQL Server Native Client applications typically receive notifications by
using the Transact-SQL RECEIVE command to read notifications from the queue
associated with the service specified in the notification options.";

private const int _numOfIterations = 10000000;

static void Main(string[] args)
{
TestConcatenation();
}

private static void TestConcatenation()
{
string strA, strB, strC, result;
TimeSpan strCreationTime, plusOperatorTime, strConcatTime,
strBuilderTime;
DateTime startTime;
StringBuilder sb;
strCreationTime = plusOperatorTime = strConcatTime = strBuilderTime =
TimeSpan.Zero;
for (int i = 0; i < _numOfIterations; i++)
{
startTime = DateTime.Now;
strA = GetRandomString(DateTime.Now.Millisecond);
strB = GetRandomString(DateTime.Now.Millisecond);
strC = GetRandomString(DateTime.Now.Millisecond);
strCreationTime += DateTime.Now - startTime;

startTime = DateTime.Now;
result = strA + strB + strC;
plusOperatorTime += DateTime.Now - startTime;

startTime = DateTime.Now;
result = string.Concat(strA, strB, strC);
strConcatTime += DateTime.Now - startTime;

startTime = DateTime.Now;
sb = new StringBuilder();
sb.AppendFormat("{0}{1}{2}", strA, strB, strC);
result = sb.ToString();
strBuilderTime += DateTime.Now - startTime;
}

//print stats
sb = new StringBuilder();
sb.AppendFormat("String creation time: {0}{1}",
strCreationTime.ToString(), Environment.NewLine);
sb.AppendFormat("Plus operator time: {0}{1}",
plusOperatorTime.ToString(), Environment.NewLine);
sb.AppendFormat("String concat time: {0}{1}", strConcatTime.ToString(),
Environment.NewLine);
sb.AppendFormat("String builder time: {0}{1}",
strBuilderTime.ToString(), Environment.NewLine);
Console.Write(sb.ToString());
}

private static string GetRandomString(int seed)
{
Random rnd;
int strStartInd, strLength;
rnd = new Random(seed);
strStartInd = rnd.Next(0, _content.Length - 1);
strLength = rnd.Next(0, _content.Length - strStartInd);
return _content.Substring(strStartInd, strLength);
}

Results for 10 000 000 iterations:

/*
String creation time: 00:03:46.3054112
Plus operator time: 00:00:20.4093472
String concat time: 00:00:25.9272816
String builder time: 00:00:50.9232240
*/

Dawid Rutyna
 
P

Peter Morris

01: Try each
02: Time them
03: See which works fastest in your scenario

Remember, if you take a part of your app that takes 1% of the total
processing time and improve its speed to almost zero the best you will speed
it up is by 1%.
 
P

Pavel Minaev

private string ConcatenateStrings(i1, i2, i3)
{
    string result = "a"+function1(i1)+"b"+function2(i2)+"c"+function3
(i3);
    return result;

}

What among the below three approaches is the best?
1. using + operator
2. using string.concat

If I remember correctly, these two are actually equivalent in C# if
you use operator+ to concatenate more than 2 arguments in a row. If
you look at the code it generates, it just calls String.Concat().
3. using stringbuilder

Unless you're explicitly setting StringBuilder.Capacity, I would
expect String.Concat to be very, very slightly faster. With Capacity
set, it will probably be the same.

In any case, the difference is likely to be undetectable even in a
tight loop, so don't bother. Just go for whatever is more readable.
 
H

Hans Kesting

Ranjith presented the following explanation :
private string ConcatenateStrings(i1, i2, i3)
{
string result = "a"+function1(i1)+"b"+function2(i2)+"c"+function3
(i3);
return result;
}

What among the below three approaches is the best?
1. using + operator
2. using string.concat
3. using stringbuilder

The function is called around 10000 times

See
http://www.yoda.arachsys.com/csharp/stringbuilder.html
for some answers

Hans Kesting
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top