.NET Fiddle

CSharp · Console

/Program.cs

using System;
using System.Diagnostics;
using System.Text;
					
public class Program
{
	public delegate string ParseMethod(byte[] Msg);
	public class Parser 
	{
		public string Name { get; private set;}
		public ParseMethod Handler { get; private set; }
		
		public Parser(string name, ParseMethod method)
		{
			Name = name;
			Handler = method;
		}
	}
	
	public static void Main()
	{
		Parser HexA = new Parser("ToHexA", ToHexA);
		Parser HexB = new Parser("ToHexB", ToHexB);
		Parser HexC = new Parser("ToHexC", ToHexC);
		
		TestCorrectness(HexA);
		TestCorrectness(HexB);
		TestCorrectness(HexC);
		
		Console.WriteLine("Big Message Performance:");
		TestPerformance(HexA, 500, 10);
		TestPerformance(HexB, 500, 10);
		TestPerformance(HexC, 500, 10);
		Console.WriteLine();
		
		Console.WriteLine("Small Message Performance:");
		TestPerformance(HexA, 10, 1000);
		TestPerformance(HexB, 10, 1000);
		TestPerformance(HexC, 10, 1000);
		Console.WriteLine();
	}
	
	private static void TestCorrectness(Parser parser)
	{
		Console.WriteLine("Testing Correctness of \"{0}(byte[] Msg)\"", parser.Name);
		Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{}));
		Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97 }));
		Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97, 98, 99, 0, 100 }));
		Console.WriteLine();
	}
	
	private static void TestPerformance(Parser parser, int MsgSize, int Runs)
	{
		Stopwatch sw = new Stopwatch();
		sw.Reset();
		
		byte[] Msg = new byte[MsgSize];
		
		sw.Start();
		for (uint i = 0; i < Runs; ++i)
		{
			parser.Handler(Msg);
		}
		sw.Stop();
		
		Console.WriteLine("Performance for \"{0}\", {1}", parser.Name, sw.Elapsed);
	}
	
	private static string ToHexA(byte[] buffer)
	{
		return
			(
				"{ 0x" +
					BitConverter.ToString(buffer).ToLower()
						.Replace("-", ", 0x") +
				" }"
			)
			.Replace(" 0x }", "}");
	}

	private static string ToHexB(byte[] buffer)
	{
		if (buffer.Length == 0) { return "{}"; }
		
		const string Preamble = "{ 0x";
		const string Delimiter = ", 0x";
		const string Epilogue = " }";
		
		string Msg = Preamble + buffer[0].ToString("x2");
		for (int i = 1; i < buffer.Length; ++i)
		{
			Msg += Delimiter + buffer[i].ToString("x2");
		}
		
		return Msg += Epilogue;
	}

	private static string ToHexC(byte[] buffer)
	{
		if (buffer.Length == 0) { return "{}"; }
		
		const string Preamble = "{ 0x";
		const string Delimiter = ", 0x";
		const string Epilogue = " }";
		
		StringBuilder HexOut = new StringBuilder(
			Preamble.Length +
			(Delimiter.Length * (buffer.Length - 1)) +
			(2 * buffer.Length) +
			Epilogue.Length
		);
		
		HexOut.Append(Preamble);
		HexOut.Append(buffer[0].ToString("x2"));
		for (int i = 1; i < buffer.Length; ++i)
		{
			HexOut.Append(Delimiter);
			HexOut.Append(buffer[i].ToString("x2"));
		}
		HexOut.Append(Epilogue);
		
		return HexOut.ToString();
	}
}
;