Count, size, length…too many choices in Ruby?

前端 未结 6 457
逝去的感伤
逝去的感伤 2021-01-29 20:18

I can\'t seem to find a definitive answer on this and I want to make sure I understand this to the \"n\'th level\" :-)


    a = { \"a\" => \"Hello\", \"b\" => \"Worl         


        
6条回答
  •  日久生厌
    2021-01-29 21:04

    There is a crucial difference for applications which make use of database connections.

    When you are using many ORMs (ActiveRecord, DataMapper, etc.) the general understanding is that .size will generate a query that requests all of the items from the database ('select * from mytable') and then give you the number of items resulting, whereas .count will generate a single query ('select count(*) from mytable') which is considerably faster.

    Because these ORMs are so prevalent I following the principle of least astonishment. In general if I have something in memory already, then I use .size, and if my code will generate a request to a database (or external service via an API) I use .count.

提交回复
热议问题