简体   繁体   English

Scala:seq.size vs 模式匹配

[英]Scala: seq.size vs pattern matching

I have to make a decision based on size of a Seq.我必须根据 Seq 的大小做出决定。

So, either I can do:所以,要么我可以这样做:

if(mySeq.size() > 0) // do your stuff

Or, I can do:或者,我可以这样做:

mySeq match {
  case x :: _ => // do your stuff
}

Which one should I prefer?我应该更喜欢哪一个?

If your checking are exactly the size > 0 or not, I prefer to如果您的检查正好是大小 > 0 或不,我更喜欢

if (mySeq.nonEmpty) { .. }

This solution without performance losing and works for all version of scala.这个解决方案没有性能损失,适用于所有版本的scala。 In my opinion nonEmpty is more intuitive than size checking.在我看来nonEmpty比大小检查更直观。

Seq is an abstraction of the underlying collection type. Seq是底层集合类型的抽象。 This presents a few problems.这提出了一些问题。

case x :: _ => won't work unless the underlying collection is a List , but you can change it to case x +: _ => for more universal coverage. case x :: _ =>除非底层集合是List ,否则将不起作用,但您可以将其更改为case x +: _ =>以获得更多的普遍覆盖。

mySeq.size might be reasonably efficient if the underlying collection is something like a Vector but it's a linear operation on a List .如果基础集合类似于Vector但它是对List的线性操作,则mySeq.size可能相当有效。

My recommendation would be to use mySeq.sizeIs > 0 (Scala 2.13).我的建议是使用mySeq.sizeIs > 0 (Scala 2.13)。 sizeIs is designed to terminate as soon as the comparison can be determined, so even on a List it should return true after traversing only one element. sizeIs旨在在比较确定后立即终止,因此即使在List它也应该在仅遍历一个元素后返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM