count vs length vs size in a collection

molasses picture molasses · Nov 19, 2008 · Viewed 93.1k times · Source

From using a number of programming languages and libraries I have noticed various terms used for the total number of elements in a collection.

The most common seem to be length, count, and size.

eg.

array.length
vector.size()
collection.count

Is there any preferred term to be used? Does it depend on what type of collection it is? ie. mutable/immutable

Is there a preference for it being a property instead of a method?

Answer

gbjbaanb picture gbjbaanb · Nov 19, 2008

Length() tends to refer to contiguous elements - a string has a length for example.

Count() tends to refer to the number of elements in a looser collection.

Size() tends to refer to the size of the collection, often this can be different from the length in cases like vectors (or strings), there may be 10 characters in a string, but storage is reserved for 20. It also may refer to number of elements - check source/documentation.

Capacity() - used to specifically refer to allocated space in collection and not number of valid elements in it. If type has both "capacity" and "size" defined then "size" usually refers to number of actual elements.

I think the main point is down to human language and idioms, the size of a string doesn't seem very obvious, whilst the length of a set is equally confusing even though they might be used to refer to the same thing (number of elements) in a collection of data.