Proposed Solution
string input = "This is a string";
string firstChar = new String(input[0], 1);
This is the least number of operations you can do.
- extract the first
char
by index
- pass the
char
to the constructor of String
String Constructor (Char, Int32)
Performance Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringPerf
{
class Program
{
static string firstChar;
static void Main(string[] args)
{
string input = "This is a sample string";
int count = 100000;
RunPerf("Warmup", 1, () =>
{
PerfContructor(input);
PerfSubstring(input);
PerfAppend(input);
});
Console.WriteLine();
Console.WriteLine();
RunPerf("Constructor", count, () => PerfContructor(input));
Console.WriteLine();
RunPerf("ToString", count, () => PerfToString(input));
Console.WriteLine();
RunPerf("Substring", count, () => PerfSubstring(input));
Console.WriteLine();
RunPerf("Append", count, () => PerfAppend(input));
Console.ReadLine();
}
static void PerfContructor(string input)
{
firstChar = new String(input[0], 1);
}
static void PerfToString(string input)
{
firstChar = input[0].ToString();
}
static void PerfSubstring(string input)
{
firstChar = input.Substring(0, 1);
}
static void PerfAppend(string input)
{
firstChar = "" + input[0];
}
static void RunPerf(string name, int count, Action action)
{
var sw = new System.Diagnostics.Stopwatch();
Console.WriteLine(string.Format("Starting perf for {0}. {1} times", name, count));
sw.Start();
for (int i = 0; i < count; i++)
{
action();
}
sw.Stop();
Console.WriteLine(string.Format("{0} completed in {1}", name, sw.Elapsed));
}
}
}
Results
Starting perf for Warmup. 1 times
Warmup completed in 00:00:00.0003153
Starting perf for Constructor. 9999999 times
Constructor completed in 00:00:00.1961569
Starting perf for ToString. 9999999 times
ToString completed in 00:00:00.2890530
Starting perf for Substring. 9999999 times
Substring completed in 00:00:00.2412256
Starting perf for Append. 9999999 times
Append completed in 00:00:00.3271857