ActiveRecord : 크기 대 개수
레일에서는 모두 사용하여 레코드의 수를 찾을 수 Model.size
및 Model.count
. 더 복잡한 쿼리를 처리하는 경우 한 방법을 다른 방법보다 사용하는 것이 유리합니까? 그것들은 어떻게 다릅니 까?
예를 들어 사진이있는 사용자가 있습니다. 사용자 테이블과 몇 장의 사진을 보여주고 싶다면 많은 인스턴스를 실행하는 user.photos.size
것이보다 빠르거나 느려 user.photos.count
집니까?
감사!
당신은 읽어야 것을 여전히 유효입니다.
필요에 따라 사용하는 기능을 조정합니다.
원래:
이미 모든 항목을로드하는 경우 (예
User.all
:length
다른 DB 쿼리를 피하기 위해 사용해야 함)아무것도로드하지 않은 경우을 사용
count
하여 DB에서 개수 쿼리를 수행하십시오.이러한 고려 사항에 신경 쓰지 않으려면 사용할
size
것을 사용하십시오.
다른 답변은 다음과 같이 말합니다.
count
SQLCOUNT
쿼리 를 수행 합니다length
결과 배열의 길이를 계산합니다size
과도한 쿼리를 피하기 위해 둘 중 가장 적합한 것을 선택하려고합니다.
그러나 한 가지 더 있습니다. 우리는 완전히 / size
다르게 행동 하는 경우를 발견했으며 간과하기가 드물기 때문에 그것을 공유 할 것이라고 생각했습니다.count
length
당신은을 사용하는 경우
:counter_cache
A의has_many
연결,size
직접 계산 캐시 된을 사용하고, 전혀 추가 질의를하지 않습니다.class Image < ActiveRecord::Base belongs_to :product, counter_cache: true end class Product < ActiveRecord::Base has_many :images end > product = Product.first # query, load product into memory > product.images.size # no query, reads the :images_count column > product.images.count # query, SQL COUNT > product.images.length # query, loads images into memory
이 동작은 Rails Guides 에 설명되어 있지만 처음 놓쳤거나 잊어 버렸습니다.
때로는 size
반환은 "잘못된 선택합니다" 해시 (무엇을 count
할 것을)
이 경우 hash 대신 정수length
를 얻는 데 사용하십시오 .
다음 전략은 모두 데이터베이스를 호출하여 COUNT(*)
쿼리 를 수행 합니다.
Model.count
Model.all.size
records = Model.all
records.count
다음은 데이터베이스의 모든 레코드를 Ruby로로드하는 것만 큼 효율적이지 않으며, 컬렉션의 크기를 계산합니다.
records = Model.all
records.size
모델에 연결이 있고 소속 개체 수 (예 :)를 찾으려면 @customer.orders.size
데이터베이스 쿼리 (디스크 읽기)를 피할 수 있습니다. 카운터 캐시를 사용하면 Rails는 캐시 값을 최신 상태로 유지하고 size
메소드 에 대한 응답으로 해당 값을 반환합니다 .
크기 기능을 사용하는 것이 좋습니다.
class Customer < ActiveRecord::Base
has_many :customer_activities
end
class CustomerActivity < ActiveRecord::Base
belongs_to :customer, counter_cache: true
end
Consider these two models. The customer has many customer activities.
If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.
Consider one example: in my database, one customer has 20,000 customer activities and I try to count the number of records of customer activities of that customer with each of count, length and size method. here below the benchmark report of all these methods.
user system total real
Count: 0.000000 0.000000 0.000000 ( 0.006105)
Size: 0.010000 0.000000 0.010000 ( 0.003797)
Length: 0.030000 0.000000 0.030000 ( 0.026481)
so I found that using :counter_cache Size is the best option to calculate the number of records.
tl;dr
- If you know you won't be needing the data use
count
. - If you know you will use or have used the data use
length
. - If you don't know what you are doing, use
size
...
count
Resolves to sending a Select count(*)...
query to the DB. The way to go if you don't need the data, but just the count.
Example: count of new messages, total elements when only a page is going to be displayed, etc.
length
Loads the required data, i.e. the query as required, and then just counts it. The way to go if you are using the data.
Example: Summary of a fully loaded table, titles of displayed data, etc.
size
It checks if the data was loaded (i.e. already in rails) if so, then just count it, otherwise it calls count. (plus the pitfalls, already mentioned in other entries).
def size
loaded? ? @records.length : count(:all)
end
What's the problem?
That you might be hitting the DB twice if you don't do it in the right order (e.g. if you render the number of elements in a table on top of the rendered table, there will be effectively 2 calls sent to the DB).
참고URL : https://stackoverflow.com/questions/6083219/activerecord-size-vs-count
'Programing' 카테고리의 다른 글
.jar 파일의 내용보기 (0) | 2020.05.14 |
---|---|
Subversion 관리 파일 이름에서 @ 문자를 이스케이프 처리하는 방법은 무엇입니까? (0) | 2020.05.14 |
AngularJS 컨트롤러를 확장하는 데 권장되는 방법은 무엇입니까? (0) | 2020.05.14 |
Django 템플릿에 주석을 넣는 방법 (0) | 2020.05.14 |
파이썬에서 문자열 날짜를 타임 스탬프로 변환 (0) | 2020.05.14 |