Scala - What is the difference between size and length of a Seq?

ScalaScala 2.10Seq

Scala Problem Overview


What is the difference between size and length of a Seq? When to use one and when the other?

scala> var a :Seq[String] = Seq("one", "two")
a: Seq[String] = List(one, two)

scala> a.size
res6: Int = 2

scala> a.length
res7: Int = 2

It's the same?

Thanks

Scala Solutions


Solution 1 - Scala

Nothing. In the Seq doc, at the size method it is clearly stated: "The size of this sequence, equivalent to length.".

Solution 2 - Scala

size is defined in GenTraversableOnce, whereas length is defined in GenSeqLike, so length only exists for Seqs, whereas size exists for all Traversables. For Seqs, however, as was already pointed out, size simply delegates to length (which probably means that, after inlining, you will get identical bytecode).

Solution 3 - Scala

In a Seq they are the same, as others have mentioned. However, for information, this is what IntelliJ warns on a scala.Array:

> Replace .size with .length on arrays and strings > > Inspection info: This > inspection reports array.size and string.size calls. While such calls > are legitimate, they require an additional implicit conversion to > SeqLike to be made. A common use case would be calling length on > arrays and strings may provide significant advantages.

Solution 4 - Scala

Nothing, one delegates to the other. See SeqLike trait.

  /** The size of this $coll, equivalent to `length`.
   *
   *  $willNotTerminateInf
   */
  override def size = length

Solution 5 - Scala

I did an experiment, using Scala version 2.12.8, and a million item list. Upon the first use, length() is 7 or 8 times faster than size(). But on the 2nd try on the same list, size() is about the same speed as length().

However, after some time, presumably the cache is gone, size() is slow() by 7 or 8 times again.

This shows that length() is preferred for sequences. It's not just another name for size().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYoBreView Question on Stackoverflow
Solution 1 - ScalaPeterView Answer on Stackoverflow
Solution 2 - ScalaJörg W MittagView Answer on Stackoverflow
Solution 3 - ScalaMark TicknerView Answer on Stackoverflow
Solution 4 - ScalasksamuelView Answer on Stackoverflow
Solution 5 - Scalauser11595225View Answer on Stackoverflow