Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any penalty between appending string vs char in C#

Tags:

When developing in Java a couple of years ago I learned that it is better to append a char if I had a single character instead of a string with one character because the VM would not have to do any lookup on the string value in its internal string pool.

string stringappend = "Hello " + name + ".";  string charappend = "Hello " + name + '.'; // better? 

When I started programming in C# I never thought of the chance that it would be the same with its "VM". I came across C# String Theory—String intern pool that states that C# also has an internal string pool (I guess it would be weird if it didn't) so my question is,

are there actually any benefits in appending a char instead of a string when concatenating to a string regarding C# or is it just jibberish?

Edit: Please disregard StringBuilder and string.Format, I am more interested in why I would replace "." with '.' in code. I am well aware of those classes and functions.

like image 543
Patrick Avatar asked Aug 02 '10 13:08

Patrick


People also ask

Can we concatenate string and char in C?

Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string. h is the header file required for string functions.

Can you add a string and a char?

A simple solution to append a character to the end of a string is using the string concatenation operator (+) . This creates a new instance of the string, since strings in Java are immutable and cannot be modified.

What is the difference between char and string in C?

The main difference between Character and String is that Character refers to a single letter, number, space, punctuation mark or a symbol that can be represented using a computer while String refers to a set of characters. In C programming, we can use char data type to store both character and string values.

Is char * Same as string?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").


2 Answers

If given a choice, I would pass a string rather than a char when calling System.String.Concat or the (equivalent) + operator.

The only overloads that I see for System.String.Concat all take either strings or objects. Since a char isn't a string, the object version would be chosen. This would cause the char to be boxed. After Concat verifies that the object reference isn't null, it would then call object.ToString on the char. It would then generate the dreaded single-character string that was being avoided in the first place, before creating the new concatinated string.

So I don't see how passing a char is going to gain anything.

Maybe someone wants to look at the Concat operation in Reflector to see if there is special handling for char?

UPDATE

As I thought, this test confirms that char is slightly slower.

using System; using System.Diagnostics;  namespace ConsoleApplication19 {     class Program     {         static void Main(string[] args)         {             TimeSpan throwAwayString = StringTest(100);             TimeSpan throwAwayChar = CharTest(100);             TimeSpan realStringTime = StringTest(10000000);             TimeSpan realCharTime = CharTest(10000000);             Console.WriteLine("string time: {0}", realStringTime);             Console.WriteLine("char time: {0}", realCharTime);             Console.ReadLine();         }          private static TimeSpan StringTest(int attemptCount)         {             Stopwatch sw = new Stopwatch();             string concatResult = string.Empty;             sw.Start();             for (int counter = 0; counter < attemptCount; counter++)                 concatResult = counter.ToString() + ".";             sw.Stop();             return sw.Elapsed;         }          private static TimeSpan CharTest(int attemptCount)         {             Stopwatch sw = new Stopwatch();             string concatResult = string.Empty;             sw.Start();             for (int counter = 0; counter < attemptCount; counter++)                 concatResult = counter.ToString() + '.';             sw.Stop();             return sw.Elapsed;         }     } } 

Results:

string time: 00:00:02.1878399 char time: 00:00:02.6671247 
like image 184
Jeffrey L Whitledge Avatar answered Oct 14 '22 20:10

Jeffrey L Whitledge


When developing in Java a couple of years ago I learned that it is better to append a char if I had a single character instead of a string with one character because the VM would not have to do any lookup on the string value in its internal string pool.

Appending a char to a String is likely to be slightly faster than appending a 1 character String because:

  • the append(char) operation doesn't have to load the string length,
  • it doesn't have to load the reference to the string characters array,
  • it doesn't have to load and add the string's start offset,
  • it doesn't have to do a bounds check on the array index, and
  • it doesn't have to increment and test a loop variable.

Take a look at the Java source code for String and related classes. You might be surprised what goes on under the hood.

The intern pool has nothing to do with it. The interning of string literals happens just once during class loading. Interning of non-literal strings occurs only if the application explicitly calls String.intern().

like image 36
Stephen C Avatar answered Oct 14 '22 22:10

Stephen C