I am using a mutable Buffer
and need to find out how many elements it has.
Both size
and length
methods are defined, inherited from separate traits.
Is there any actual performance difference, or can they be considered exact synonyms?
I am using a mutable Buffer
and need to find out how many elements it has.
Both size
and length
methods are defined, inherited from separate traits.
Is there any actual performance difference, or can they be considered exact synonyms?
In this case, they can be considered synonyms. You may want to watch out with some other cases such as
Array
- whilst length and size will always return the same result, in versions prior to Scala 2.10 there may be a boxing overhead for callingsize
(which is provided by a Scala wrapper around the Array), whereaslength
is provided by the underlying Java Array.In Scala 2.10, this overhead has been removed by use of a value class providing the
size
method, so you should feel free to use whichever method you like.They are synonyms, as the scaladoc for
Buffer.size
states:The scaladoc for
Buffer.length
is explicit too:Simple advice: refer to the scaladoc before asking a question.
UPDATE: Just saw your edit adding mention of performance. As Daniel C. Sobral aid, one is normally always implemented in term of the other, so they have the same performance.
As of Scala-2.11, these methods may have different performance. For example, consider this code:
Running this on my amd64 computer gives about 2423834 nanos time (varies from time to time).
Now, if I change the
length
method tosize
, it will become about 70764719 nanos time.This is more than 20x slower.
Why does it happen? I didn't dig it through, I don't know. But there are scenarios where
length
andsize
perform drastically different.They are synonyms, mostly a result of Java's decision of having
size
for collections andlength
forArray
andString
. One will always be defined in terms of the other, and you can easily see which is which by looking at the source code, the link for which is provided on scaladoc. Just find the defining trait, open the source code, and search fordef size
ordef length
.