Created
October 30, 2013 16:55
-
-
Save alexmoore/7236112 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Numerics; | |
using System.Globalization; | |
using System.Text; | |
using System.Diagnostics; | |
using System.Threading; | |
namespace StringPaddingTest | |
{ | |
class MainClass | |
{ | |
static BigInteger b = ulong.MaxValue; | |
static BigInteger b2 = BigInteger.Multiply (b, 1000000000000000000); | |
public static void Main (string[] args) | |
{ | |
TestOld (); | |
TestNew (); | |
TestOld (); | |
TestNew (); | |
TestOld (); | |
TestNew (); | |
} | |
static void TestOriginal () | |
{ | |
var s = new Stopwatch (); | |
s.Start (); | |
for (int x = 0; x < 100000; x++) { | |
b.ToLexicographicId (); | |
b2.ToLexicographicId (); | |
} | |
s.Stop (); | |
Console.WriteLine ("Original time: {0}", s.ElapsedMilliseconds); | |
} | |
static void TestSimple () | |
{ | |
var s = new Stopwatch (); | |
s.Start (); | |
for (int x = 0; x < 100000; x++) { | |
b.ToLexyId (); | |
b2.ToLexyId (); | |
} | |
s.Stop (); | |
Console.WriteLine ("Simple time: {0}", s.ElapsedMilliseconds); | |
} | |
} | |
public static class IdExtensions | |
{ | |
// Most NoSQL storage technologies order records by a single Id field | |
// that is lexicographically sorted. This will cause flake-ids to be | |
// incorrectly sorted. In order to handle this, this extension class | |
// provides the ability to front-pad an id with 0s so that it will sort | |
// correctly in a lexicographic system. | |
//Maximum 128 bit integer: 340282366920938463463374607431768211455 | |
// 0 1 2 3 | |
// 123456789012345678901234567890123456789 | |
public static readonly string PADDING = "000000000000000000000000000000000000000"; | |
public static string ToLexicographicId(this BigInteger id) | |
{ | |
var stringId = id.ToString(); | |
var padding = PADDING.ToCharArray(); | |
stringId.CopyTo(0, padding, 39 - stringId.Length, stringId.Length); | |
return new string(padding); | |
} | |
} | |
public static class IdExtensions2 | |
{ | |
public static string ToLexyId(this BigInteger id) | |
{ | |
return id.ToString().PadLeft (39, '0'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment