Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def measure(f: () => Unit) {
- val start = System.currentTimeMillis()
- f()
- println(s"Elapsed: ${System.currentTimeMillis()-start}ms")
- }
- val str = ". ? + * | { } [ ] ( ) \" \\ # @ & < > ~"
- measure(() =>
- for { i <- 0 to 10000000 } {
- val escaped = str.replaceAll("""([\.\?\+\*\|\{\}\[\]\(\)\"\\\#\@\&\<\>\~])""", """\\\\$1""")
- }
- )
- val r = java.util.regex.Pattern.compile("""([\.\?\+\*\|\{\}\[\]\(\)\"\\\#\@\&\<\>\~])""")
- measure(() =>
- for { i <- 0 to 10000000 } {
- val escaped = r.matcher(str).replaceAll("""\\\\$1""")
- }
- )
- measure(() =>
- for { i <- 0 to 10000000 } {
- val escaped = escape(str)
- }
- )
- def escape(str: String): String = {
- val chars = str.toCharArray()
- val sb = new StringBuffer(2 * chars.length)
- var i = 0
- while (i < str.length) {
- val c = chars(i)
- (c: @scala.annotation.switch) match {
- case '.' | '?' | '+' | '*' | '|' | '{' |
- '}' | '[' | ']' | '(' | ')' | '"' |
- '\\' | '#' | '@' | '&' | '<' | '>' | '~' => sb.append("""\\\\""").append(c)
- case _ => sb.append(c)
- }
- i += 1
- }
- sb.toString()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement