Char
, String
A char
can be converted to a one-character string
. There are several ways to do this. The clearest method is the ToString
method.
Other implementations may have better performance. For example, we can use the string
constructor. We test these methods.
Here we have a character "x" and we convert it into a string
with 2 different method calls. We use ToString
, and the string
constructor.
using System; char value = 'x'; // Perform conversions. string result = value.ToString(); Console.WriteLine("RESULT LENGTH: {0}", result.Length); string result2 = new string(value, 1); Console.WriteLine("RESULT2 LENGTH: {0}", result2.Length);RESULT LENGTH: 1 RESULT2 LENGTH: 1
In the Main
entry point, both methods return an equivalent string
from the char
argument. Their results are equal. We test their runtime speed.
Method1
, uses the string
constructor to convert a char
to a string
.ToString
virtual
method on the char
type.string
constructor is a slightly faster approach. But other approaches, like lookup tables, are probably even better.using System; using System.Diagnostics; class Program { static string Method1(char value) { return new string(value, 1); } static string Method2(char value) { return value.ToString(); } const int _max = 100000000; static void Main() { Console.WriteLine(Method1('c')); Console.WriteLine(Method2('c')); var s1 = Stopwatch.StartNew(); // Version 1: use string constructor. for (int i = 0; i < _max; i++) { Method1('c'); } s1.Stop(); // Version 2: use ToString. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { Method2('c'); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }c c 10.37 ns 10.48 ns
On my system, the results consistently indicated that the string
constructor was slightly faster. And this held true regardless of what order the methods were tested.
string
constructor.We could implement a lookup table to get cached 1-char strings. The char
could be used as an index into a precomputed array of strings.
string
allocation into an array element load. This improves performance.It is simplest to just use the ToString
method call. We can sometimes use Substring
to take a one-character string
from an input string
, avoiding the char
type.