count vs length vs size in a collection

2019-01-01 05:11发布

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?

9条回答
伤终究还是伤i
2楼-- · 2019-01-01 05:41

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.

查看更多
心情的温度
3楼-- · 2019-01-01 05:41

Count I think is the most obvious term to use if you're looking for the number of items in a collection. That should even be obvious to new programmers who haven't become particularly attached to a given language yet.

And it should be a property as that's what it is: a description (aka property) of the collection. A method would imply that it has to do something to the collection to get the number of items and that just seems unintuitive.

查看更多
情到深处是孤独
4楼-- · 2019-01-01 05:41

Hmm...I would not use size. Because this might be confused with size in bytes. Length - could make some sense for arrays, as long as they are supposed to use consequent bytes of memory. Though...length...in what? Count is clear. How many elements. I would use count.

About property/method, I would use property to mark it's fast, and method to mark it's slow.

And, the most important - I would stick to the standards of the languages/libraries you are using.

查看更多
登录 后发表回答