Using a StringBuilder
will help, but even more so if you declare the initial size to be the actual length of the expected output. That avoids resizing the internal array of the StringBuilder
at runtime. Also, accessing a String's char array directly is a little bit faster than using charAt(int)
on String
-- the reference is direct instead of making a method reference to the array.
public static String getRandomString(String characterSet){
final char[] chars = characterSet.toCharArray();
final int size = 500000;
StringBuilder sb = new StringBuilder(size);
Random rand = new Random();
for(int i=0;i<size;i++){
sb.append(chars[rand.nextInt(chars.length)]);
}
return sb.toString();
}