Ruby best practices: count, length, size

When to use which:

Hash

  • size and length both call RHASH_SIZE which is O(1)
  • count is enumerable.count which is O(n) – use only with block
  • best practice: length without block, count with block

Array

  • size is an alias for length
  • length calls RARRAY_LEN which is O(1)
  • count is O(n) – use only with block
  • best practice: length without block, count with block

ActiveRecord

  • count and size create a COUNT query which is often faster than alternative
  • length creates an array and calls length which is usually slower
  • best practice: count

Leave a Reply

Your email address will not be published. Required fields are marked *