diff options
author | Yorick Peterse <yorickpeterse@gmail.com> | 2017-08-14 16:22:09 +0300 |
---|---|---|
committer | Yorick Peterse <yorickpeterse@gmail.com> | 2017-08-14 19:00:28 +0300 |
commit | aef9f1eb9405e9bab92b15f5c99bf06eaf28a5d6 (patch) | |
tree | 01ebae601e9df77c1b2887e0783b73b30f833b2b /app/services/projects/forks_count_service.rb | |
parent | 21a6898b10ed75f6260e72467b9e1f839d48456c (diff) |
Cache the number of forks of a project
The number of forks of a project doesn't change very frequently and
running a COUNT(*) every time this information is requested can be quite
expensive. We also end up running such a COUNT(*) query at least twice
on the homepage of a project.
By caching this data and refreshing it when necessary we can reduce
project homepage loading times by around 60 milliseconds (based on the
timings of https://gitlab.com/gitlab-org/gitlab-ce).
Diffstat (limited to 'app/services/projects/forks_count_service.rb')
-rw-r--r-- | app/services/projects/forks_count_service.rb | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/app/services/projects/forks_count_service.rb b/app/services/projects/forks_count_service.rb new file mode 100644 index 00000000000..e2e2b1da91d --- /dev/null +++ b/app/services/projects/forks_count_service.rb @@ -0,0 +1,30 @@ +module Projects + # Service class for getting and caching the number of forks of a project. + class ForksCountService + def initialize(project) + @project = project + end + + def count + Rails.cache.fetch(cache_key) { uncached_count } + end + + def refresh_cache + Rails.cache.write(cache_key, uncached_count) + end + + def delete_cache + Rails.cache.delete(cache_key) + end + + private + + def uncached_count + @project.forks.count + end + + def cache_key + ['projects', @project.id, 'forks_count'] + end + end +end |