请求某人解释这个 Scala/Java 差异 -
使用 Scala 模式匹配
scala> def scalaRegex(count: Int) = {
| val t1 = System.currentTimeMillis
| val r_r = "test".r
| val str = "test"
| for (i <- 0 to count) {
| str match {
| case r_r =>
| }
| }
| val t2 = System.currentTimeMillis
| val diff = t2 - t1
| println(t2); println(t1); println(diff)
| }
scalaRegex: (count: Int)Unit
scala> scalaRegex(1000000000)
1425976261692
1425976261102
590
使用 Java 的简单方法来匹配正则表达式的 -
scala> def javaRegex(count:Int) = {
| val t1 = System.currentTimeMillis
| val r_r = "test".r.pattern
| val str = "test"
| for (i <- 0 to count) {
| r_r.matcher(str).matches()
| }
| val t2 = System.currentTimeMillis
| val diff = t2 - t1
| println(t2); println(t1); println(diff)
| }
javaRegex: (count: Int)Unit
scala> javaRegex(1000000000)
1425976399868
1425976335679
64189
那是 100 倍的差异 - 发生了什么?
最佳答案
嗯...你对 scala 中的术语模式匹配
感到困惑。
这不是正则表达式模式匹配
。
scala> val regex = "test".r
regex: scala.util.matching.Regex = test
scala> val str1 = "test"
str1: String = test
scala> val str2 = "qwerty"
str2: String = qwerty
scala> str1 match {
| case regex => println( "yes" )
| }
yes
scala> str2 match {
| case regex => println( "yes" )
| }
yes
这里没有正则表达式匹配。
这甚至适用于 Int
。
scala> val i = 5
i: Int = 5
scala> str2 match {
| case i => println( "yes" )
| }
yes
在 scala 中,如果你在 variable case
上模式匹配
...它总是会匹配...它的行为就像一个 if( true )
其他语言。
scala> val i = 5
i: Int = 5
// here str2 can be any valid scala variable... Int, Long, List, String etc...
scala> str2 match {
| case i => println( "I will always get printed, irrespective of str2." )
| }
I will always get printed, irrespective of str2.
所以...在您的 Scala 示例中,它只是使用 count
循环,在每个循环中执行 if( true )
然后打印时间,而在您的 Java 中例如,您实际上是在进行正则表达式模式匹配。因此,您的 Java 示例花费了大量时间。
关于regex - Scala 与 Java 正则表达式匹配 : Big performance difference: Why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28959675/