Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there performance reasons to prefer size over length or count in Ruby?

In Airbnb's Ruby Style Guide one suggestion reads:

Prefer size over either length or count for performance reasons.

What would these performance reasons be?

like image 791
jeporcher Avatar asked Nov 26 '18 11:11

jeporcher


1 Answers

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:

  • For 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.
  • For 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.
  • for String it's used to count substrings.

All in all, I would say that

Prefer size or length over count for performance reasons.

would be more accurate.

like image 168
Marcin Kołodziej Avatar answered Nov 17 '22 06:11

Marcin Kołodziej