Random alphanumeric password generator with GOTOs

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
5
down vote

favorite












I was inspired after this thread on Stack Overflow to create a random 8 character alphanumeric password generator.



Sadly, it is closed, so I cannot provide an answer there. Anyway, here is the code. Let me know if there are any bugs/bias going on.



using System.Collections.Generic;
using System.Security.Cryptography;

public class AlphanumericGen

public virtual string Generate(byte length)

ICollection<char> chars = new LinkedList<char>();
var buffer = new byte[1];
short counter = 0;
using (var rng = new RNGCryptoServiceProvider())

while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (nextChar >= '0' && nextChar <= '9')

goto addChar;


if (nextChar >= 'A' && nextChar <= 'Z')

goto addChar;


if (nextChar >= 'a' && nextChar <= 'z')

goto addChar;


continue;

addChar:
chars.Add(nextChar);
++counter;



return string.Concat(chars);











share|improve this question



















  • 2




    Is there a particular reason you're using goto? In this example it's pretty obvious what it's doing, but I've seen some legacy code that was a crippling headache to figure out what a goto was doing when a simple function would have been as clear as glass.
    – Shelby115
    1 hour ago






  • 1




    Is using goto an essential motivator for this code? If not, then it probably doesn't warrant a mention in the title.
    – Toby Speight
    46 mins ago














up vote
5
down vote

favorite












I was inspired after this thread on Stack Overflow to create a random 8 character alphanumeric password generator.



Sadly, it is closed, so I cannot provide an answer there. Anyway, here is the code. Let me know if there are any bugs/bias going on.



using System.Collections.Generic;
using System.Security.Cryptography;

public class AlphanumericGen

public virtual string Generate(byte length)

ICollection<char> chars = new LinkedList<char>();
var buffer = new byte[1];
short counter = 0;
using (var rng = new RNGCryptoServiceProvider())

while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (nextChar >= '0' && nextChar <= '9')

goto addChar;


if (nextChar >= 'A' && nextChar <= 'Z')

goto addChar;


if (nextChar >= 'a' && nextChar <= 'z')

goto addChar;


continue;

addChar:
chars.Add(nextChar);
++counter;



return string.Concat(chars);











share|improve this question



















  • 2




    Is there a particular reason you're using goto? In this example it's pretty obvious what it's doing, but I've seen some legacy code that was a crippling headache to figure out what a goto was doing when a simple function would have been as clear as glass.
    – Shelby115
    1 hour ago






  • 1




    Is using goto an essential motivator for this code? If not, then it probably doesn't warrant a mention in the title.
    – Toby Speight
    46 mins ago












up vote
5
down vote

favorite









up vote
5
down vote

favorite











I was inspired after this thread on Stack Overflow to create a random 8 character alphanumeric password generator.



Sadly, it is closed, so I cannot provide an answer there. Anyway, here is the code. Let me know if there are any bugs/bias going on.



using System.Collections.Generic;
using System.Security.Cryptography;

public class AlphanumericGen

public virtual string Generate(byte length)

ICollection<char> chars = new LinkedList<char>();
var buffer = new byte[1];
short counter = 0;
using (var rng = new RNGCryptoServiceProvider())

while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (nextChar >= '0' && nextChar <= '9')

goto addChar;


if (nextChar >= 'A' && nextChar <= 'Z')

goto addChar;


if (nextChar >= 'a' && nextChar <= 'z')

goto addChar;


continue;

addChar:
chars.Add(nextChar);
++counter;



return string.Concat(chars);











share|improve this question















I was inspired after this thread on Stack Overflow to create a random 8 character alphanumeric password generator.



Sadly, it is closed, so I cannot provide an answer there. Anyway, here is the code. Let me know if there are any bugs/bias going on.



using System.Collections.Generic;
using System.Security.Cryptography;

public class AlphanumericGen

public virtual string Generate(byte length)

ICollection<char> chars = new LinkedList<char>();
var buffer = new byte[1];
short counter = 0;
using (var rng = new RNGCryptoServiceProvider())

while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (nextChar >= '0' && nextChar <= '9')

goto addChar;


if (nextChar >= 'A' && nextChar <= 'Z')

goto addChar;


if (nextChar >= 'a' && nextChar <= 'z')

goto addChar;


continue;

addChar:
chars.Add(nextChar);
++counter;



return string.Concat(chars);








c# random






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 1 hour ago









t3chb0t

33.1k744106




33.1k744106










asked 1 hour ago









Sam Pearson

26219




26219







  • 2




    Is there a particular reason you're using goto? In this example it's pretty obvious what it's doing, but I've seen some legacy code that was a crippling headache to figure out what a goto was doing when a simple function would have been as clear as glass.
    – Shelby115
    1 hour ago






  • 1




    Is using goto an essential motivator for this code? If not, then it probably doesn't warrant a mention in the title.
    – Toby Speight
    46 mins ago












  • 2




    Is there a particular reason you're using goto? In this example it's pretty obvious what it's doing, but I've seen some legacy code that was a crippling headache to figure out what a goto was doing when a simple function would have been as clear as glass.
    – Shelby115
    1 hour ago






  • 1




    Is using goto an essential motivator for this code? If not, then it probably doesn't warrant a mention in the title.
    – Toby Speight
    46 mins ago







2




2




Is there a particular reason you're using goto? In this example it's pretty obvious what it's doing, but I've seen some legacy code that was a crippling headache to figure out what a goto was doing when a simple function would have been as clear as glass.
– Shelby115
1 hour ago




Is there a particular reason you're using goto? In this example it's pretty obvious what it's doing, but I've seen some legacy code that was a crippling headache to figure out what a goto was doing when a simple function would have been as clear as glass.
– Shelby115
1 hour ago




1




1




Is using goto an essential motivator for this code? If not, then it probably doesn't warrant a mention in the title.
– Toby Speight
46 mins ago




Is using goto an essential motivator for this code? If not, then it probably doesn't warrant a mention in the title.
– Toby Speight
46 mins ago










3 Answers
3






active

oldest

votes

















up vote
6
down vote













As a general rule of thumb, any time you feel the need to use goto, take a couple of aspirin and lay down until the feeling passes. They probably should have been deprecated decades ago.



In this particular case, using a string of allowed characters and randomly picking an index in that string would do away with your goto's.



I think too a StringBuilder would do a lot better for storing the characters that a LinkedList.






share|improve this answer






















  • I think it wouldn't be wise to ban goto entirely... expression trees use them so it's good to be familiar with them ;-]
    – t3chb0t
    59 mins ago











  • @t3chb0t - It seems to me that since Goto is an overloaded extension in the Expression class there shouldn't be a need for them in the general language.
    – tinstaafl
    51 mins ago











  • Thanks for the StringBuilder advice!
    – Sam Pearson
    25 mins ago

















up vote
4
down vote













Data structure



Why are you using a LinkedList<char>? Linked lists involve a lot of overhead for each node. You know exactly how long the result should be, so why not write to a char array?



Actually, you may want to consider returning the result as a char rather than as a string. A security-sensitive program may wish to wipe the contents of the secret by overwriting it with NUL bytes, rather than waiting for the garbage collector to clean up the string.



Flow control



goto should be avoided, and its use is not justified here.



The loop is a bit clumsy, referring to counter all over the place.



char chars = new char[length];
using (var rng = new RNGCryptoServiceProvider())

for (int counter = 0; counter < length; )

return new string(chars);



Algorithm



The algorithm is rather inefficient:



  • It reads a byte at a time from the random number generator. .GetBytes() is thread safe, so each call should incur some synchronization overhead.

  • It throws away most of the bytes it reads, keeping each byte with a probability of $62 over 256$.

A smarter approach would be to fetch a bit more than $3 over 4 mathrmlength$ random bytes, base64-encode it, and discard just the resulting + and / characters.






share|improve this answer






















  • Linked lists involve a lot of overhead for each node. - do they? I many cases they are pretty damn fast.
    – t3chb0t
    52 mins ago






  • 2




    @t3chb0t "Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values, because the storage overhead for the links may exceed by a factor of two or more the size of the data. … It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools." Definitely much much worse than a char for this application.
    – 200_success
    49 mins ago










  • ok, in general this is true but for a small password generator not really critical - I wouldn't panic - unless OP is generating several millions of them - they are like linq, convinient and with convenience there is a price :-)
    – t3chb0t
    41 mins ago











  • oh, and I have bad news... for 1_000_000 calls this is 4 seconds slower than the original version... now I'm curious why... I'll have to ask the profiler...
    – t3chb0t
    34 mins ago











  • ok, for some reason your code is calling GetBytes 33 million times and OP's only 8 million... whereas AddLast adds only 245ms of overhead - so nothing to worry about ;-]
    – t3chb0t
    18 mins ago


















up vote
2
down vote













Readability & GoTo



If you want to do the same action for 3 different if-statements make them one if-statement or make them a function. goto causes massive headaches when it's been months since you've touched the code and you come back to it not remembering a thing. Not to mention || is short circuit so you're not really losing anything on performance.



rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

var isNumber = nextChar >= '0' && nextChar <= '9';
var isUppercaseLetter = nextChar >= 'A' && nextChar <= 'Z';
var isLowercaseLetter = nextChar >= 'a' && nextChar <= 'z';

if (isNumber || isUppercaseLetter || isLowercaseLetter)

chars.Add(nextChar);
++counter;



Now with the conditions named even an idiot like me can come in here and see that you're checking if the character is alpha-numeric. If you wanted to make it even more obvious you could go one step further and make it a function.



public bool IsAlphaNumericCharacter(char c)

var isNumber = c >= '0' && c <= '9';
var isUppercaseLetter = c >= 'A' && c <= 'Z';
var isLowercaseLetter = c >= 'a' && c <= 'z';

return isNumber



Then your loop becomes shorter and clearer.



while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (IsAlphaNumericCharacter(nextChar))

chars.Add(nextChar);
++counter;




Bytes



Is there a particular reason you're using byte for length instead of int? Also, was there a reason for var buffer = new byte[1]; being an array instead of just var buffer = new byte();



If the answer to both of those questions is no, then you could have a character array of size length instead of a LinkedList<char>.



StringBuilder



StringBuilder could be beneficial, but if you're at a low amount of characters (like your link suggests) then it's probably not going to make a difference performance-wise (always best to test yourself instead of listening to a stranger on the internet though :P).






share|improve this answer
















  • 1




    You might be doing more work than the usual short-circuit equivalent, by storing comparison results in those (nicely named!) variables before testing. Unless your compiler optimises that away, of course.
    – Toby Speight
    48 mins ago











Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207171%2frandom-alphanumeric-password-generator-with-gotos%23new-answer', 'question_page');

);

Post as a guest






























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
6
down vote













As a general rule of thumb, any time you feel the need to use goto, take a couple of aspirin and lay down until the feeling passes. They probably should have been deprecated decades ago.



In this particular case, using a string of allowed characters and randomly picking an index in that string would do away with your goto's.



I think too a StringBuilder would do a lot better for storing the characters that a LinkedList.






share|improve this answer






















  • I think it wouldn't be wise to ban goto entirely... expression trees use them so it's good to be familiar with them ;-]
    – t3chb0t
    59 mins ago











  • @t3chb0t - It seems to me that since Goto is an overloaded extension in the Expression class there shouldn't be a need for them in the general language.
    – tinstaafl
    51 mins ago











  • Thanks for the StringBuilder advice!
    – Sam Pearson
    25 mins ago














up vote
6
down vote













As a general rule of thumb, any time you feel the need to use goto, take a couple of aspirin and lay down until the feeling passes. They probably should have been deprecated decades ago.



In this particular case, using a string of allowed characters and randomly picking an index in that string would do away with your goto's.



I think too a StringBuilder would do a lot better for storing the characters that a LinkedList.






share|improve this answer






















  • I think it wouldn't be wise to ban goto entirely... expression trees use them so it's good to be familiar with them ;-]
    – t3chb0t
    59 mins ago











  • @t3chb0t - It seems to me that since Goto is an overloaded extension in the Expression class there shouldn't be a need for them in the general language.
    – tinstaafl
    51 mins ago











  • Thanks for the StringBuilder advice!
    – Sam Pearson
    25 mins ago












up vote
6
down vote










up vote
6
down vote









As a general rule of thumb, any time you feel the need to use goto, take a couple of aspirin and lay down until the feeling passes. They probably should have been deprecated decades ago.



In this particular case, using a string of allowed characters and randomly picking an index in that string would do away with your goto's.



I think too a StringBuilder would do a lot better for storing the characters that a LinkedList.






share|improve this answer














As a general rule of thumb, any time you feel the need to use goto, take a couple of aspirin and lay down until the feeling passes. They probably should have been deprecated decades ago.



In this particular case, using a string of allowed characters and randomly picking an index in that string would do away with your goto's.



I think too a StringBuilder would do a lot better for storing the characters that a LinkedList.







share|improve this answer














share|improve this answer



share|improve this answer








edited 27 mins ago

























answered 1 hour ago









tinstaafl

5,872625




5,872625











  • I think it wouldn't be wise to ban goto entirely... expression trees use them so it's good to be familiar with them ;-]
    – t3chb0t
    59 mins ago











  • @t3chb0t - It seems to me that since Goto is an overloaded extension in the Expression class there shouldn't be a need for them in the general language.
    – tinstaafl
    51 mins ago











  • Thanks for the StringBuilder advice!
    – Sam Pearson
    25 mins ago
















  • I think it wouldn't be wise to ban goto entirely... expression trees use them so it's good to be familiar with them ;-]
    – t3chb0t
    59 mins ago











  • @t3chb0t - It seems to me that since Goto is an overloaded extension in the Expression class there shouldn't be a need for them in the general language.
    – tinstaafl
    51 mins ago











  • Thanks for the StringBuilder advice!
    – Sam Pearson
    25 mins ago















I think it wouldn't be wise to ban goto entirely... expression trees use them so it's good to be familiar with them ;-]
– t3chb0t
59 mins ago





I think it wouldn't be wise to ban goto entirely... expression trees use them so it's good to be familiar with them ;-]
– t3chb0t
59 mins ago













@t3chb0t - It seems to me that since Goto is an overloaded extension in the Expression class there shouldn't be a need for them in the general language.
– tinstaafl
51 mins ago





@t3chb0t - It seems to me that since Goto is an overloaded extension in the Expression class there shouldn't be a need for them in the general language.
– tinstaafl
51 mins ago













Thanks for the StringBuilder advice!
– Sam Pearson
25 mins ago




Thanks for the StringBuilder advice!
– Sam Pearson
25 mins ago












up vote
4
down vote













Data structure



Why are you using a LinkedList<char>? Linked lists involve a lot of overhead for each node. You know exactly how long the result should be, so why not write to a char array?



Actually, you may want to consider returning the result as a char rather than as a string. A security-sensitive program may wish to wipe the contents of the secret by overwriting it with NUL bytes, rather than waiting for the garbage collector to clean up the string.



Flow control



goto should be avoided, and its use is not justified here.



The loop is a bit clumsy, referring to counter all over the place.



char chars = new char[length];
using (var rng = new RNGCryptoServiceProvider())

for (int counter = 0; counter < length; )

return new string(chars);



Algorithm



The algorithm is rather inefficient:



  • It reads a byte at a time from the random number generator. .GetBytes() is thread safe, so each call should incur some synchronization overhead.

  • It throws away most of the bytes it reads, keeping each byte with a probability of $62 over 256$.

A smarter approach would be to fetch a bit more than $3 over 4 mathrmlength$ random bytes, base64-encode it, and discard just the resulting + and / characters.






share|improve this answer






















  • Linked lists involve a lot of overhead for each node. - do they? I many cases they are pretty damn fast.
    – t3chb0t
    52 mins ago






  • 2




    @t3chb0t "Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values, because the storage overhead for the links may exceed by a factor of two or more the size of the data. … It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools." Definitely much much worse than a char for this application.
    – 200_success
    49 mins ago










  • ok, in general this is true but for a small password generator not really critical - I wouldn't panic - unless OP is generating several millions of them - they are like linq, convinient and with convenience there is a price :-)
    – t3chb0t
    41 mins ago











  • oh, and I have bad news... for 1_000_000 calls this is 4 seconds slower than the original version... now I'm curious why... I'll have to ask the profiler...
    – t3chb0t
    34 mins ago











  • ok, for some reason your code is calling GetBytes 33 million times and OP's only 8 million... whereas AddLast adds only 245ms of overhead - so nothing to worry about ;-]
    – t3chb0t
    18 mins ago















up vote
4
down vote













Data structure



Why are you using a LinkedList<char>? Linked lists involve a lot of overhead for each node. You know exactly how long the result should be, so why not write to a char array?



Actually, you may want to consider returning the result as a char rather than as a string. A security-sensitive program may wish to wipe the contents of the secret by overwriting it with NUL bytes, rather than waiting for the garbage collector to clean up the string.



Flow control



goto should be avoided, and its use is not justified here.



The loop is a bit clumsy, referring to counter all over the place.



char chars = new char[length];
using (var rng = new RNGCryptoServiceProvider())

for (int counter = 0; counter < length; )

return new string(chars);



Algorithm



The algorithm is rather inefficient:



  • It reads a byte at a time from the random number generator. .GetBytes() is thread safe, so each call should incur some synchronization overhead.

  • It throws away most of the bytes it reads, keeping each byte with a probability of $62 over 256$.

A smarter approach would be to fetch a bit more than $3 over 4 mathrmlength$ random bytes, base64-encode it, and discard just the resulting + and / characters.






share|improve this answer






















  • Linked lists involve a lot of overhead for each node. - do they? I many cases they are pretty damn fast.
    – t3chb0t
    52 mins ago






  • 2




    @t3chb0t "Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values, because the storage overhead for the links may exceed by a factor of two or more the size of the data. … It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools." Definitely much much worse than a char for this application.
    – 200_success
    49 mins ago










  • ok, in general this is true but for a small password generator not really critical - I wouldn't panic - unless OP is generating several millions of them - they are like linq, convinient and with convenience there is a price :-)
    – t3chb0t
    41 mins ago











  • oh, and I have bad news... for 1_000_000 calls this is 4 seconds slower than the original version... now I'm curious why... I'll have to ask the profiler...
    – t3chb0t
    34 mins ago











  • ok, for some reason your code is calling GetBytes 33 million times and OP's only 8 million... whereas AddLast adds only 245ms of overhead - so nothing to worry about ;-]
    – t3chb0t
    18 mins ago













up vote
4
down vote










up vote
4
down vote









Data structure



Why are you using a LinkedList<char>? Linked lists involve a lot of overhead for each node. You know exactly how long the result should be, so why not write to a char array?



Actually, you may want to consider returning the result as a char rather than as a string. A security-sensitive program may wish to wipe the contents of the secret by overwriting it with NUL bytes, rather than waiting for the garbage collector to clean up the string.



Flow control



goto should be avoided, and its use is not justified here.



The loop is a bit clumsy, referring to counter all over the place.



char chars = new char[length];
using (var rng = new RNGCryptoServiceProvider())

for (int counter = 0; counter < length; )

return new string(chars);



Algorithm



The algorithm is rather inefficient:



  • It reads a byte at a time from the random number generator. .GetBytes() is thread safe, so each call should incur some synchronization overhead.

  • It throws away most of the bytes it reads, keeping each byte with a probability of $62 over 256$.

A smarter approach would be to fetch a bit more than $3 over 4 mathrmlength$ random bytes, base64-encode it, and discard just the resulting + and / characters.






share|improve this answer














Data structure



Why are you using a LinkedList<char>? Linked lists involve a lot of overhead for each node. You know exactly how long the result should be, so why not write to a char array?



Actually, you may want to consider returning the result as a char rather than as a string. A security-sensitive program may wish to wipe the contents of the secret by overwriting it with NUL bytes, rather than waiting for the garbage collector to clean up the string.



Flow control



goto should be avoided, and its use is not justified here.



The loop is a bit clumsy, referring to counter all over the place.



char chars = new char[length];
using (var rng = new RNGCryptoServiceProvider())

for (int counter = 0; counter < length; )

return new string(chars);



Algorithm



The algorithm is rather inefficient:



  • It reads a byte at a time from the random number generator. .GetBytes() is thread safe, so each call should incur some synchronization overhead.

  • It throws away most of the bytes it reads, keeping each byte with a probability of $62 over 256$.

A smarter approach would be to fetch a bit more than $3 over 4 mathrmlength$ random bytes, base64-encode it, and discard just the resulting + and / characters.







share|improve this answer














share|improve this answer



share|improve this answer








edited 38 mins ago

























answered 55 mins ago









200_success

126k14148409




126k14148409











  • Linked lists involve a lot of overhead for each node. - do they? I many cases they are pretty damn fast.
    – t3chb0t
    52 mins ago






  • 2




    @t3chb0t "Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values, because the storage overhead for the links may exceed by a factor of two or more the size of the data. … It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools." Definitely much much worse than a char for this application.
    – 200_success
    49 mins ago










  • ok, in general this is true but for a small password generator not really critical - I wouldn't panic - unless OP is generating several millions of them - they are like linq, convinient and with convenience there is a price :-)
    – t3chb0t
    41 mins ago











  • oh, and I have bad news... for 1_000_000 calls this is 4 seconds slower than the original version... now I'm curious why... I'll have to ask the profiler...
    – t3chb0t
    34 mins ago











  • ok, for some reason your code is calling GetBytes 33 million times and OP's only 8 million... whereas AddLast adds only 245ms of overhead - so nothing to worry about ;-]
    – t3chb0t
    18 mins ago

















  • Linked lists involve a lot of overhead for each node. - do they? I many cases they are pretty damn fast.
    – t3chb0t
    52 mins ago






  • 2




    @t3chb0t "Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values, because the storage overhead for the links may exceed by a factor of two or more the size of the data. … It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools." Definitely much much worse than a char for this application.
    – 200_success
    49 mins ago










  • ok, in general this is true but for a small password generator not really critical - I wouldn't panic - unless OP is generating several millions of them - they are like linq, convinient and with convenience there is a price :-)
    – t3chb0t
    41 mins ago











  • oh, and I have bad news... for 1_000_000 calls this is 4 seconds slower than the original version... now I'm curious why... I'll have to ask the profiler...
    – t3chb0t
    34 mins ago











  • ok, for some reason your code is calling GetBytes 33 million times and OP's only 8 million... whereas AddLast adds only 245ms of overhead - so nothing to worry about ;-]
    – t3chb0t
    18 mins ago
















Linked lists involve a lot of overhead for each node. - do they? I many cases they are pretty damn fast.
– t3chb0t
52 mins ago




Linked lists involve a lot of overhead for each node. - do they? I many cases they are pretty damn fast.
– t3chb0t
52 mins ago




2




2




@t3chb0t "Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values, because the storage overhead for the links may exceed by a factor of two or more the size of the data. … It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools." Definitely much much worse than a char for this application.
– 200_success
49 mins ago




@t3chb0t "Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values, because the storage overhead for the links may exceed by a factor of two or more the size of the data. … It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools." Definitely much much worse than a char for this application.
– 200_success
49 mins ago












ok, in general this is true but for a small password generator not really critical - I wouldn't panic - unless OP is generating several millions of them - they are like linq, convinient and with convenience there is a price :-)
– t3chb0t
41 mins ago





ok, in general this is true but for a small password generator not really critical - I wouldn't panic - unless OP is generating several millions of them - they are like linq, convinient and with convenience there is a price :-)
– t3chb0t
41 mins ago













oh, and I have bad news... for 1_000_000 calls this is 4 seconds slower than the original version... now I'm curious why... I'll have to ask the profiler...
– t3chb0t
34 mins ago





oh, and I have bad news... for 1_000_000 calls this is 4 seconds slower than the original version... now I'm curious why... I'll have to ask the profiler...
– t3chb0t
34 mins ago













ok, for some reason your code is calling GetBytes 33 million times and OP's only 8 million... whereas AddLast adds only 245ms of overhead - so nothing to worry about ;-]
– t3chb0t
18 mins ago





ok, for some reason your code is calling GetBytes 33 million times and OP's only 8 million... whereas AddLast adds only 245ms of overhead - so nothing to worry about ;-]
– t3chb0t
18 mins ago











up vote
2
down vote













Readability & GoTo



If you want to do the same action for 3 different if-statements make them one if-statement or make them a function. goto causes massive headaches when it's been months since you've touched the code and you come back to it not remembering a thing. Not to mention || is short circuit so you're not really losing anything on performance.



rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

var isNumber = nextChar >= '0' && nextChar <= '9';
var isUppercaseLetter = nextChar >= 'A' && nextChar <= 'Z';
var isLowercaseLetter = nextChar >= 'a' && nextChar <= 'z';

if (isNumber || isUppercaseLetter || isLowercaseLetter)

chars.Add(nextChar);
++counter;



Now with the conditions named even an idiot like me can come in here and see that you're checking if the character is alpha-numeric. If you wanted to make it even more obvious you could go one step further and make it a function.



public bool IsAlphaNumericCharacter(char c)

var isNumber = c >= '0' && c <= '9';
var isUppercaseLetter = c >= 'A' && c <= 'Z';
var isLowercaseLetter = c >= 'a' && c <= 'z';

return isNumber



Then your loop becomes shorter and clearer.



while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (IsAlphaNumericCharacter(nextChar))

chars.Add(nextChar);
++counter;




Bytes



Is there a particular reason you're using byte for length instead of int? Also, was there a reason for var buffer = new byte[1]; being an array instead of just var buffer = new byte();



If the answer to both of those questions is no, then you could have a character array of size length instead of a LinkedList<char>.



StringBuilder



StringBuilder could be beneficial, but if you're at a low amount of characters (like your link suggests) then it's probably not going to make a difference performance-wise (always best to test yourself instead of listening to a stranger on the internet though :P).






share|improve this answer
















  • 1




    You might be doing more work than the usual short-circuit equivalent, by storing comparison results in those (nicely named!) variables before testing. Unless your compiler optimises that away, of course.
    – Toby Speight
    48 mins ago















up vote
2
down vote













Readability & GoTo



If you want to do the same action for 3 different if-statements make them one if-statement or make them a function. goto causes massive headaches when it's been months since you've touched the code and you come back to it not remembering a thing. Not to mention || is short circuit so you're not really losing anything on performance.



rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

var isNumber = nextChar >= '0' && nextChar <= '9';
var isUppercaseLetter = nextChar >= 'A' && nextChar <= 'Z';
var isLowercaseLetter = nextChar >= 'a' && nextChar <= 'z';

if (isNumber || isUppercaseLetter || isLowercaseLetter)

chars.Add(nextChar);
++counter;



Now with the conditions named even an idiot like me can come in here and see that you're checking if the character is alpha-numeric. If you wanted to make it even more obvious you could go one step further and make it a function.



public bool IsAlphaNumericCharacter(char c)

var isNumber = c >= '0' && c <= '9';
var isUppercaseLetter = c >= 'A' && c <= 'Z';
var isLowercaseLetter = c >= 'a' && c <= 'z';

return isNumber



Then your loop becomes shorter and clearer.



while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (IsAlphaNumericCharacter(nextChar))

chars.Add(nextChar);
++counter;




Bytes



Is there a particular reason you're using byte for length instead of int? Also, was there a reason for var buffer = new byte[1]; being an array instead of just var buffer = new byte();



If the answer to both of those questions is no, then you could have a character array of size length instead of a LinkedList<char>.



StringBuilder



StringBuilder could be beneficial, but if you're at a low amount of characters (like your link suggests) then it's probably not going to make a difference performance-wise (always best to test yourself instead of listening to a stranger on the internet though :P).






share|improve this answer
















  • 1




    You might be doing more work than the usual short-circuit equivalent, by storing comparison results in those (nicely named!) variables before testing. Unless your compiler optimises that away, of course.
    – Toby Speight
    48 mins ago













up vote
2
down vote










up vote
2
down vote









Readability & GoTo



If you want to do the same action for 3 different if-statements make them one if-statement or make them a function. goto causes massive headaches when it's been months since you've touched the code and you come back to it not remembering a thing. Not to mention || is short circuit so you're not really losing anything on performance.



rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

var isNumber = nextChar >= '0' && nextChar <= '9';
var isUppercaseLetter = nextChar >= 'A' && nextChar <= 'Z';
var isLowercaseLetter = nextChar >= 'a' && nextChar <= 'z';

if (isNumber || isUppercaseLetter || isLowercaseLetter)

chars.Add(nextChar);
++counter;



Now with the conditions named even an idiot like me can come in here and see that you're checking if the character is alpha-numeric. If you wanted to make it even more obvious you could go one step further and make it a function.



public bool IsAlphaNumericCharacter(char c)

var isNumber = c >= '0' && c <= '9';
var isUppercaseLetter = c >= 'A' && c <= 'Z';
var isLowercaseLetter = c >= 'a' && c <= 'z';

return isNumber



Then your loop becomes shorter and clearer.



while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (IsAlphaNumericCharacter(nextChar))

chars.Add(nextChar);
++counter;




Bytes



Is there a particular reason you're using byte for length instead of int? Also, was there a reason for var buffer = new byte[1]; being an array instead of just var buffer = new byte();



If the answer to both of those questions is no, then you could have a character array of size length instead of a LinkedList<char>.



StringBuilder



StringBuilder could be beneficial, but if you're at a low amount of characters (like your link suggests) then it's probably not going to make a difference performance-wise (always best to test yourself instead of listening to a stranger on the internet though :P).






share|improve this answer












Readability & GoTo



If you want to do the same action for 3 different if-statements make them one if-statement or make them a function. goto causes massive headaches when it's been months since you've touched the code and you come back to it not remembering a thing. Not to mention || is short circuit so you're not really losing anything on performance.



rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

var isNumber = nextChar >= '0' && nextChar <= '9';
var isUppercaseLetter = nextChar >= 'A' && nextChar <= 'Z';
var isLowercaseLetter = nextChar >= 'a' && nextChar <= 'z';

if (isNumber || isUppercaseLetter || isLowercaseLetter)

chars.Add(nextChar);
++counter;



Now with the conditions named even an idiot like me can come in here and see that you're checking if the character is alpha-numeric. If you wanted to make it even more obvious you could go one step further and make it a function.



public bool IsAlphaNumericCharacter(char c)

var isNumber = c >= '0' && c <= '9';
var isUppercaseLetter = c >= 'A' && c <= 'Z';
var isLowercaseLetter = c >= 'a' && c <= 'z';

return isNumber



Then your loop becomes shorter and clearer.



while (counter < length)

rng.GetBytes(buffer);
var nextChar = (char)buffer[0];

if (IsAlphaNumericCharacter(nextChar))

chars.Add(nextChar);
++counter;




Bytes



Is there a particular reason you're using byte for length instead of int? Also, was there a reason for var buffer = new byte[1]; being an array instead of just var buffer = new byte();



If the answer to both of those questions is no, then you could have a character array of size length instead of a LinkedList<char>.



StringBuilder



StringBuilder could be beneficial, but if you're at a low amount of characters (like your link suggests) then it's probably not going to make a difference performance-wise (always best to test yourself instead of listening to a stranger on the internet though :P).







share|improve this answer












share|improve this answer



share|improve this answer










answered 1 hour ago









Shelby115

1,416516




1,416516







  • 1




    You might be doing more work than the usual short-circuit equivalent, by storing comparison results in those (nicely named!) variables before testing. Unless your compiler optimises that away, of course.
    – Toby Speight
    48 mins ago













  • 1




    You might be doing more work than the usual short-circuit equivalent, by storing comparison results in those (nicely named!) variables before testing. Unless your compiler optimises that away, of course.
    – Toby Speight
    48 mins ago








1




1




You might be doing more work than the usual short-circuit equivalent, by storing comparison results in those (nicely named!) variables before testing. Unless your compiler optimises that away, of course.
– Toby Speight
48 mins ago





You might be doing more work than the usual short-circuit equivalent, by storing comparison results in those (nicely named!) variables before testing. Unless your compiler optimises that away, of course.
– Toby Speight
48 mins ago


















 

draft saved


draft discarded















































 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207171%2frandom-alphanumeric-password-generator-with-gotos%23new-answer', 'question_page');

);

Post as a guest













































































Popular posts from this blog

How to check contact read email or not when send email to Individual?

Bahrain

Postfix configuration issue with fips on centos 7; mailgun relay