C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# program that converts chars to strings
using System;
class Program
{
static void Main()
{
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);
}
}
Output
RESULT LENGTH: 1
RESULT2 LENGTH: 1
Version 1: The first method here, Method1, uses the string constructor to convert a char to a string.
Version 2: This version of the code calls the ToString virtual method on the char type.
Result: Using the string constructor is a slightly faster approach. But other approaches, like lookup tables, are probably even better.
C# program that times char conversion
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"));
Console.Read();
}
}
Output
c
c
10.37 ns
10.48 ns
Note: There is probably somewhat less overhead involved in calling the string constructor.
And: This would change a string allocation into an array element load. This improves performance.
ROT13