Skip to content
Browse files

string perf tweaks, tests #359

Signed-off-by: Stuart Halloway <stu@thinkrelevance.com>
  • Loading branch information...
1 parent 07fc530 commit b7f211356c27ba099f3dbe116539dbd9efa421df David Liebke and Stuart Halloway committed with stuarthalloway
Showing with 29 additions and 14 deletions.
  1. +19 −9 src/clj/clojure/string.clj
  2. +5 −0 test/clojure/test_clojure.clj
  3. +5 −5 test/clojure/test_clojure/string.clj
View
28 src/clj/clojure/string.clj
@@ -67,7 +67,7 @@
(if (string? replacement)
(.replaceFirst (re-matcher ^Pattern match s) ^String replacement)
(replace-first-by s match replacement))
- :default (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))
+ :else (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))
(defn ^String join
@@ -118,23 +118,33 @@
(defn ^String triml
"Removes whitespace from the left side of string."
[^String s]
- (replace s #"^\s+" ""))
+ (loop [index (int 0)]
+ (if (= (.length s) index)
+ ""
+ (if (Character/isWhitespace (.charAt s index))
+ (recur (inc index))
+ (.substring s index)))))
(defn ^String trimr
"Removes whitespace from the right side of string."
[^String s]
- (replace s #"\s+$" ""))
+ (loop [index (.length s)]
+ (if (zero? index)
+ ""
+ (if (Character/isWhitespace (.charAt s (dec index)))
+ (recur (dec index))
+ (.substring s 0 index)))))
-(defn ^String trim-nl
+(defn ^String trim-newline
"Removes all trailing newline \\n or return \\r characters from
string. Note: String.trim() is similar and faster."
[^String s]
- (loop [offset (.length s)]
- (if (zero? offset)
+ (loop [index (.length s)]
+ (if (zero? index)
""
- (let [ch (.charAt s (dec offset))]
+ (let [ch (.charAt s (dec index))]
(if (or (= ch \newline) (= ch \return))
- (recur (dec offset))
- (.substring s 0 offset))))))
+ (recur (dec index))
+ (.substring s 0 index))))))
View
5 test/clojure/test_clojure.clj
@@ -58,6 +58,11 @@
:rt
:repl
:java.io
+ :string
+ :java.javadoc
+ :java.shell
+ :transients
+ :def
])
(def test-namespaces
View
10 test/clojure/test_clojure/string.clj
@@ -27,11 +27,11 @@
"1" \, [1]
"1 and-a 2 and-a 3" " and-a " [1 2 3]))
-(deftest t-trim-nl
- (is (= "foo" (s/trim-nl "foo\n")))
- (is (= "foo" (s/trim-nl "foo\r\n")))
- (is (= "foo" (s/trim-nl "foo")))
- (is (= "" (s/trim-nl ""))))
+(deftest t-trim-newline
+ (is (= "foo" (s/trim-newline "foo\n")))
+ (is (= "foo" (s/trim-newline "foo\r\n")))
+ (is (= "foo" (s/trim-newline "foo")))
+ (is (= "" (s/trim-newline ""))))
(deftest t-capitalize
(is (= "Foobar" (s/capitalize "foobar")))

0 comments on commit b7f2113

Please sign in to comment.
Something went wrong with that request. Please try again.