[PATCH] [lang] Performance boost for RandomNumberUtils

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

[PATCH] [lang] Performance boost for RandomNumberUtils

Shaun Kalley
This patch replaces the StringBuffer used in RandomStringUtils with a
char array, resulting in a significant performance increase (better than
30% by my testing).  It doesn't change the existing API, and it passes
the provided unit tests.

Thanks,
Shaun Kalley

Index: trunk/src/java/org/apache/commons/lang/RandomStringUtils.java
===================================================================
--- trunk/src/java/org/apache/commons/lang/RandomStringUtils.java (revision 179476)
+++ trunk/src/java/org/apache/commons/lang/RandomStringUtils.java (working copy)
@@ -230,26 +230,25 @@
             }
         }
 
-        StringBuffer buffer = new StringBuffer();
+        char[] buffer = new char[count];
         int gap = end - start;
 
-        while (count-- != 0) {
+        for (int i = 0; i < count; i++) {
             char ch;
             if (chars == null) {
                 ch = (char) (random.nextInt(gap) + start);
             } else {
                 ch = chars[random.nextInt(gap) + start];
             }
-            if ((letters && numbers && Character.isLetterOrDigit(ch))
-                || (letters && Character.isLetter(ch))
+            if ((letters && Character.isLetter(ch))
                 || (numbers && Character.isDigit(ch))
                 || (!letters && !numbers)) {
-                buffer.append(ch);
+                buffer[i] = ch;
             } else {
-                count++;
+                i--;
             }
         }
-        return buffer.toString();
+        return new String(buffer);
     }
 
     /**


---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]
Reply | Threaded
Open this post in threaded view
|

RE: [PATCH] [lang] Performance boost for RandomNumberUtils

Gary Gregory
HI Shaun:

Could you please create a Bugzilla ticket and attach your patch there?

Thanks!
Gary

-----Original Message-----
From: Shaun Kalley [mailto:[hidden email]]
Sent: Wednesday, June 01, 2005 6:42 PM
To: [hidden email]
Subject: [PATCH] [lang] Performance boost for RandomNumberUtils

This patch replaces the StringBuffer used in RandomStringUtils with a
char array, resulting in a significant performance increase (better than

30% by my testing).  It doesn't change the existing API, and it passes
the provided unit tests.

Thanks,
Shaun Kalley

---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]