In Airbnb's Ruby Style Guide one suggestion reads:
Prefer
sizeover eitherlengthorcountfor performance reasons.
What would these performance reasons be?
It seems a bit wrong, for most commonly used cases (Array, Hash, String), size and length are either aliases or are implemented in the same way (you can read more here or check the implementation of each method) and will run in O(1).
count however:
Hash is not redefined and will fallback to Enumerable#count, which means its complexity will be O(n) as all key-values will be traversed.Array it is redefined (Array#count) and at the very least it will check the number of arguments given which is something that neither Array#size nor Array#length have to do.String it's used to count substrings.All in all, I would say that
Prefer
sizeorlengthovercountfor performance reasons.
would be more accurate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With