C# - What is the most efficient way to generate 10 character random alphanumeric string in?
What is the most efficient way to generate 开发者_运维技巧10-character random alphanumeric string in c#?
http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx
string randomName = Path.GetRandomFileName();
randomName = randomName.Replace(".", string.Empty);
// take substring...
eg:
?Path.GetRandomFileName();
"rlwi1uew.5ha"
?Path.GetRandomFileName();
"gcwhcoiy.vxl"
?Path.GetRandomFileName();
"2pzyljzf.k41"
?Path.GetRandomFileName();
"kyjzcccf.d3c"
var buffer = new byte[5];
new Random().NextBytes(buffer);
Console.WriteLine(string.Join("", buffer.Select(b => b.ToString("X2"))));
var buffer = new byte[15];
new Random().NextBytes(buffer);
string rnd = Convert.ToBase64String (buffer).Substring (10);
The only problem I see with this is that it also uses +
and /
, so you'll have to replace them with something, too.
string rnd = Convert.ToBase64String (buffer)
.Substring (10)
.Replace ('/', '0')
.Replace ('+', '1');
Guid is pretty fast
Guid.NewGuid().ToString("N").Substring(0, 10);
From MSDN
A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.
It might not be unique for a billion requests since you need only 10 characters. But it generates a string from 0 to 9 and A to F.
Performance
Tested using
public static void Test(Action a)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (var i = 0; i < 10000; ++i)
a();
sw.Stop();
Console.WriteLine("ms: {0} ticks: {1}", sw.ElapsedMilliseconds, sw.ElapsedTicks);
}
Guid method
Test(() =>
{
var xxx = Guid.NewGuid().ToString("N").Substring(0, 10);
});
// Result
// 6 ms
// 17273 ticks
Bytes method
Test(() =>
{
var buffer = new byte[5];
new Random().NextBytes(buffer);
var x = string.Join("", buffer.Select(b => b.ToString("X2")));
});
// Result:
// 57 ms
// 165642 ticks
It is up to you to pick between high speed
or high reliability
.
精彩评论