Search code examples
c#performanceref

c# ref for speed


I understand full the ref word in the .NET

Since using the same variable, would increase speed to use ref instead of making copy?

I find bottleneck to be in password general.

Here is my codes

protected internal string GetSecurePasswordString(string legalChars, int length)
{
    Random myRandom = new Random();
    string myString = "";
    for (int i = 0; i < length; i++)
    {
        int charPos = myRandom.Next(0, legalChars.Length - 1);
        myString = myString + legalChars[charPos].ToString();
    }
    return myString;
}

is better to ref before legalchars?


Solution

  • No, you shouldn't pass the string reference by reference.

    However, you are creating several strings pointlessly. If you're creating long passwords, that could be why it's a bottleneck. Here's a faster implementation:

    protected internal string GetSecurePasswordString(string legalChars, int length)
    {
        Random myRandom = new Random();
        char[] chars = new char[length];
        for (int i = 0; i < length; i++)
        {
            int charPos = myRandom.Next(0, legalChars.Length - 1);
            chars[i] = legalChars[charPos];
        }
        return new string(chars);
    }
    

    However, it still has three big flaws:

    • It creates a new instance of Random each time. If you call this method twice in quick succession, you'll get the same password twice. Bad idea.
    • The upper bound specified in a Random.Next() call is exclusive - so you'll never use the last character of legalChars.
    • It uses System.Random, which is not meant to be in any way cryptographically secure. Given that this is meant to be for a "secure password" you should consider using something like System.Security.Cryptography.RandomNumberGenerator. It's more work to do so because the API is harder, but you'll end up with a more secure system (if you do it properly).

    You might also want to consider using SecureString, if you get really paranoid.