Reputation: 186
I have two string values and I want to sum lengths of these two strings. How can calculate best way?
first:
string firstStr = "this a first message";
string secondStr = "this a second message";
int total = firstStr.Length + secondStr.Length;
second:
string firstStr = "this a first message";
string secondStr = "this a second message";
int total = (firstStr + secondStr).Length;
or other?
Upvotes: 1
Views: 354
Reputation: 1681
i did a couple of test runs, doing 1M runs of each approach
first approach: 38,189 ms
second approach: 50,4055 ms
here is the code:
class Program
{
static void Main(string[] args)
{
Stopwatch watch;
watch = new Stopwatch();
watch.Start();
First();
watch.Stop();
Trace.WriteLine(string.Format("first: {0} ms",watch.Elapsed.TotalMilliseconds));
watch = new Stopwatch();
watch.Start();
Second();
watch.Stop();
Trace.WriteLine(string.Format("second: {0} ms", watch.Elapsed.TotalMilliseconds));
}
static void First()
{
for (int i = 0; i < 1000000; i++)
{
string firstStr = "this a first message";
string secondStr = "this a second message";
int total = firstStr.Length + secondStr.Length;
}
}
static void Second()
{
for (int i = 0; i < 1000000; i++)
{
string firstStr = "this a first message";
string secondStr = "this a second message";
int total = (firstStr + secondStr).Length;
}
}
}
Upvotes: -1
Reputation: 727077
The first way is more efficient, because it simply adds two numbers.
The second way is wasteful, because it creates a new object, copies the content of two strings into it, counts the length, and then discards the temporary object - hardly an efficient use of the CPU!
Another way to compare the two is to compare their asymptotic times - O(1) for the first solution, and O(m+n) for the second solution. The first computation completes in constant time, because string lengths are readily available. The second computation requires copying the content of each string, which is linear.
Upvotes: 10
Reputation: 3915
The first is more efficient, because it doesn't involve the creation of a third string through concatenation. In the first case you just have to add up the length of two objects you already have in memory, without wasting memory / time.
Upvotes: 0
Reputation: 1825
Second version is creating a new string instance and then getting its length. It should be expensive. But whatever the difference would be it would be negligible for the above line of codes.
Upvotes: 2
Reputation: 12857
Your first option doesn't create a new string, so in my book it's better.
int total = firstStr.Length + secondStr.Length;
Upvotes: 0
Reputation: 296
First is probably faster because your string object already know his length. The second you add a concatenation operation.
Upvotes: 6