Skip to content

Instantly share code, notes, and snippets.

@ig-sinicyn
Last active March 31, 2016 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ig-sinicyn/857ed5e239138e17e7e830bd4c82ff89 to your computer and use it in GitHub Desktop.
Save ig-sinicyn/857ed5e239138e17e7e830bd4c82ff89 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
#pragma warning disable 1591
// ReSharper disable ArrangeTypeModifiers
public static class FormattableStringFactory
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#pragma warning disable CS0436
public static FormattableString Create(string s, params object[] args) => new FormattableString(s, args);
#pragma warning restore CS0436
}
}
namespace System
{
public struct FormattableString : IFormattable
{
private readonly string _s;
private readonly object[] _args;
public FormattableString(string s, object[] args)
{
_s = s;
_args = args;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() => string.Format(_s, _args);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ToString(string ignored, IFormatProvider formatProvider) => string.Format(formatProvider, _s, _args);
}
}
#pragma warning restore 1591
namespace Samples
{
class Program
{
static void Assert(bool x, string message)
{
if (!x)
throw new InvalidOperationException(message);
}
static void Assert(bool x, string messageFormat, params object[] args)
{
if (!x)
throw new InvalidOperationException(string.Format(messageFormat, args));
}
#pragma warning disable CS0436
static void Assert(bool x, FormattableString messageFormat)
#pragma warning restore CS0436
{
if (!x)
throw new InvalidOperationException(messageFormat.ToString());
}
static void Main(string[] args)
{
const int Count = 10 * 1000 * 1000;
int x = 2;
var sw = Stopwatch.StartNew();
for (int i = 0; i < Count; i++)
{
Assert(x > 0, "Value of x ({0}) should be greater than zero.", x);
}
var t1 = sw.Elapsed;
sw.Restart();
for (int i = 0; i < Count; i++)
{
Assert(x > 0, $"Value of x ({x}) should be greater than zero.");
}
var t2 = sw.Elapsed;
sw.Restart();
for (int i = 0; i < Count; i++)
{
#pragma warning disable CS0436
Assert(x > 0, (FormattableString)$"Value of x ({x}) be should be greater than zero.");
#pragma warning restore CS0436
}
var t3 = sw.Elapsed;
Console.WriteLine("Format+args: " + t1.TotalMilliseconds);
Console.WriteLine("Interpolated: " + t2.TotalMilliseconds);
Console.WriteLine("Formattable(explicit): " + t3.TotalMilliseconds);
Console.WriteLine("\r\nDone.");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment