Skip to content

Conversation

rosa
Copy link
Member

@rosa rosa commented Dec 11, 2020

This PR switches offset calculation from a O(2^n) implementation (where n is the number of bits used to
represent the page number) to O(1).

Before:

portion = GearedPagination::PortionAtOffset.new(page_number: 100000000, per_page: GearedPagination::Ratios.new)
Benchmark.bm do |x|
  x.report { portion.offset }
end

     user     system      total        real
11.741485   0.296831  12.038316 ( 12.049057)

After:

portion = GearedPagination::PortionAtOffset.new(page_number: 100000000, per_page: GearedPagination::Ratios.new)
Benchmark.bm do |x|
  x.report { portion.offset }
end

   user     system      total        real
0.000027   0.000007   0.000034 (  0.000030)

Apart from this, this also includes a small fix for the per_page parameter, as it was not working due to values there being passed to Ratios as strings, which means we'd always fail to calculate the offset. Tests were passing because all of them used the first page, which uses offset 0 independently of the configured ratios. With strings, and any other page > 1, a TypeError: String can't be coerced into Integer would be raised as we'd try to perform arithmetic operations on strings.

rosa added 2 commits December 11, 2020 22:13
per_page parameter was not working as parameters would get passed to
Ratios as strings, which means we'd always fail to calculte the offset.
Tests were passing because all of them used the first page, which uses
offset 0 independently of the configured ratios. With strings, and any
other page > 1, a `TypeError: String can't be coerced into Integer`
would be raised as we'd try to perform arithmetic operations on strings.
Switch from O(2^n) (where n is the number of bits used to
represent the page number) to O(1).

Before:
```
portion = GearedPagination::PortionAtOffset.new(page_number: 100000000, per_page: GearedPagination::Ratios.new)
Benchmark.bm do |x|
  x.report { portion.offset }
end

     user     system      total        real
11.741485   0.296831  12.038316 ( 12.049057)
```

After:
```
portion = GearedPagination::PortionAtOffset.new(page_number: 100000000, per_page: GearedPagination::Ratios.new)
Benchmark.bm do |x|
  x.report { portion.offset }
end

   user     system      total        real
0.000027   0.000007   0.000034 (  0.000030)
```
@rosa rosa force-pushed the speed-up-offset-calculation branch from 31d893a to dfe380d Compare December 14, 2020 15:18
@rosa rosa merged commit 4ca705c into master Dec 14, 2020
@rosa rosa deleted the speed-up-offset-calculation branch December 14, 2020 15:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant