斯卡拉COM prehension性能斯卡、性能、COM、prehension

2023-09-11 00:04:23 作者:待我兵戎马卸给你天下i

为什么

for (
  a <- 1 to 1000;
  b <- 1 to 1000 - a;
  c <- 1 to 1000 - a - b;
  if (a * a + b * b == c * c && a + b + c == 1000)
) println((a, b, c, a * b * c))

266毫秒

266 ms

慢然后:

for (a <- 1 to 1000)
  for (b <- 1 to 1000 - a)
    for (c <- 1 to 1000 - a - b)
      if (a * a + b * b == c * c)
        if (a + b + c == 1000)
          println((a, b, c, a * b * c))

62毫秒

如果我理解正确的,这应该是一样的吗?

If I understand correct this should be the same?

加工答案后解决方法:

for (
  a <- 1 to 1000;
  b <- 1 to (1000 - a)
) {
  val c = (1000 - a - b)
  if (a * a + b * b == c * c)
    println((a, b, c, a * b * c))
}

9毫秒

推荐答案

您的理解是错误的。

for(x <- coll) if(condition) dosomething

将转化为

coll.foreach{x => if(condition) dosomething }

for(x <- coll if(condition))  dosomething

这将转化为

coll.withFilter(x => condition).foreach{ x => dosomething }

您可以看看 Scala语言规格网络阳离子6.16 了解更多详情。

You can look into The Scala Language Specification 6.16 for more details.

 
精彩推荐
图片推荐