davydovanton / kan

Simple, functional authorization library and role management for ruby
http://www.kanrb.org
MIT License
232 stars 12 forks source link

[ENHANCE] Optimize Abilities Call and Reduce Object Creation #13

Closed berniechiu closed 6 years ago

berniechiu commented 6 years ago

I think this is a GOOD FIRST PR here?? lol

Objective

I'm trying to optimize the check abilities here by mapping with the hash, thus reduce the repeated object creation since the within same ability scope, I think we're using the same AbilitiesList right?

Feature

By mapping with the current ability key, the same AbilitiesList instance won't be repeatedly generated~ Hooray!!

How to Test

See the RSpec test passed~ or need to write extra one (not sure here lol) I'll attach a benchmark later~

davydovanton commented 6 years ago

Hey, nice catch :+1: Could you provide some benchmarks before merge? :)

berniechiu commented 6 years ago

Example code (Just use the sample code from README here) Benchmark with this https://github.com/SamSaffron/memory_profiler, not sure if there's any better one for GC and memory benchmarking tool : )

n = 50000
report = MemoryProfiler.report do
  n.times do
    abilities['post.read'].call(current_user, post)
    abilities['post.delete'].call(current_user, post)
  end
end
report.pretty_print

Before

Total allocated: 64000000 bytes (1500000 objects)
Total retained:  0 bytes (0 objects)

allocated memory by gem
-----------------------------------
  52000000  kan/lib
  12000000  other

After

Total allocated: 60000000 bytes (1400000 objects)
Total retained:  0 bytes (0 objects)

allocated memory by gem
-----------------------------------
  48000000  kan/lib
  12000000  other
davydovanton commented 6 years ago

Wow, looks great! Thanks for your work! 💗