/ Published in: Java
                    
                                        Works almost 9x faster than a regex pattern, and memory usage is better (because Matcher objects aren't created).
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
 /* instead of Pattern p = Pattern.compile("[\\s]+$"); // start timing p.matcher(str).replaceAll(""); The alternative method below averages 400ns, compared to 3500ns of the regex above */ int len = str.length(); char[] val = str.toCharArray(); while ((0 < len) && (val[len - 1] <= ' ')) { len--; } return (len < str.length()) ? str.substring(0, len) : str; } /* Similarly, using a StringCharacterIterator is also faster (although memory usage is worse) - averages 500ns */ int len = str.length(); .previous()) { len --; } return ((len < str.length())) ? str.substring(0, len) : str; }
Comments
                    Subscribe to comments
                
                