First, it is likely that you probably do not need to improve the performance of this method. The likelihood that the method is not called often enough that its optimization will noticeably change the overall performance of the application. Before optimizing at this level, you must profile , otherwise you risk wasting time on things that do not matter.
Secondly, even if this is an effective optimization, you still need to profile the application to find out which optimizations work best ... and whether the optimization work really mattered.
If (hypothetically) I had to do this as quickly as possible, I would try this:
private static final char[] subset = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray(); private static final Random prng = new Random(); ... public static String randomString(final int length) { char[] chars = new char[length]; final int subsetLength = subsetLength; for (int i = 0; i < length; i++) { int index = prng.nextInt(subsetLength); chars[i] = subset[index]; } return new String(chars); }
In short:
- Do not create a new instance of
Random
each time. This is probably the biggest optimization since instantiating usually involves a system call to get random seed. - Do not use
StringBuilder
when char[]
working fine. - Avoid the (small)
charAt
overhead. - Raise one-time tasks from loops and method calls, where possible.
(Note that points 3. and 4. may not be practical, i.e. the JIT compiler can be smart enough to do the same optimizations for you ... if you just enable it.)
source share