Skip to content

Commit f8e7f78

Browse files
committed
Reuse regex matcher in replaceAll calls
Regex compilation is expensive, so we should re-use the matcher over multiple replaceAll calls in: - StdNames.str.sanitize - Text's lengthWithoutAnsi
1 parent 7036ed8 commit f8e7f78

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

compiler/src/dotty/tools/dotc/core/StdNames.scala

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package core
33

44
import scala.collection.mutable
55
import scala.annotation.switch
6+
import scala.annotation.internal.sharable
67
import Names._
78
import Symbols._
89
import Contexts._
@@ -40,7 +41,9 @@ object StdNames {
4041
inline val Tuple = "Tuple"
4142
inline val Product = "Product"
4243

43-
def sanitize(str: String): String = str.replaceAll("""[<>]""", """\$""").nn
44+
@sharable
45+
private val disallowed = java.util.regex.Pattern.compile("""[<>]""").nn
46+
def sanitize(str: String): String = disallowed.matcher(str).nn.replaceAll("""\$""").nn
4447
}
4548

4649
abstract class DefinedNames[N <: Name] {

compiler/src/dotty/tools/dotc/printing/Texts.scala

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
package dotty.tools.dotc
22
package printing
3+
import scala.annotation.internal.sharable
34

45
object Texts {
56

7+
@sharable
8+
private val ansi = java.util.regex.Pattern.compile("\u001b\\[\\d+m").nn
9+
610
sealed abstract class Text {
711

812
protected def indentMargin: Int = 2
@@ -70,7 +74,7 @@ object Texts {
7074
else appendIndented(that)(width)
7175

7276
private def lengthWithoutAnsi(str: String): Int =
73-
str.replaceAll("\u001b\\[\\d+m", "").nn.length
77+
ansi.matcher(str).nn.replaceAll("").nn.length
7478

7579
def layout(width: Int): Text = this match {
7680
case Str(s, _) =>

0 commit comments

Comments
 (0)