Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance Improvement (Generating Random String of any length)

Generate a random string of any particular length. I know this question has been asked many times, I wrote this code below, I just wanted to know is there any better approach then the below code I wrote? Or we can make the below code more efficient?

public static void main(String[] args) {
    String s = randomString(25);
    System.out.println(s);
}

public static String randomString(final int length) {
    StringBuilder sb = new StringBuilder();
    Random r = new Random();
    String subset = "0123456789abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < length; i++) {
        int index = r.nextInt(subset.length());
        char c = subset.charAt( index );
        sb.append( c );
    }
    return sb.toString();
}
like image 632
arsenal Avatar asked Jan 17 '23 13:01

arsenal


1 Answers

Since you know the length ahead of time, setup the StringBuilder with a capacity:

StringBuilder sb = new StringBuilder(length);

This alone eliminates the unnecessary resizing of the internal array within the StringBuilder.

That being said, you're probably better off using a char[] array instead of StringBuilder, and just represent subset as a char[] as well.

private static final char [] subset = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();

char buf[] = new char[length];
for (int i=0;i<buf.length;i++) {
  int index = r.nextInt(subset.length);
  buf[i] = subset[index];
}

return new String(buf);

There's some subtle gains to be had here by avoiding some function call overhead to "charAt" and "append". As well as eliminating some of the memory and allocation time overhead for the StringBuilder. In general, if you know the size of a string you are building, it's a bit more efficient to work directly with the char arrays.

like image 95
Matt Avatar answered Jan 19 '23 04:01

Matt