Performance bugfix

@the-teacher the-teacher released this Apr 4, 2014 · 26 commits to master since this release

TheSotrableTree is render-helper for AwesomeNestedSet trees. The Magick of this gem in simplicity of implementation. Gem used recursive function to render tree. But recursion is very slow when tree contain more then 100 items. This problem solved with index-hash. Yesterday I patched this index-hash, because I found logic mistake. Previous versions should works fine, but current version more stable. Please read details to know more.


Render Helper

In previous versions I used boost-array to accelerate rendering. it was defined with

    opts = {
      :boost => []

And was builded once with

if opts[:boost].empty?
  tree.each do |item|
    num = item.parent_id || 0
    opts[:boost][num] = [] unless opts[:boost][num]
    opts[:boost][num].push item

But I forgot how ruby array is work. If you have 2 elements in tree with ids: 1 and 100500 and do something like this

opts[:boost][1] = "value"
opts[:boost][100500] = "value"

And it will create array for 100500 elements, where 100498 elements will be nil. It was my terrible mistake


Solution is very easy - replace boost-array with boost-hash

:boost => {} 
if opts[:boost].empty?
  tree.each do |item|
    num = item.parent_id || 0
    opts[:boost][num.to_s] = [] unless opts[:boost][num.to_s]
    opts[:boost][num.to_s].push item


on my macbook air

Boost OFF: 8000 nodes, 3 levels deep => (Views: 176281.9ms | ActiveRecord: 189.8ms)

Boost ON: 8000 nodes, 3 levels deep   => (Views: 8987.8ms | ActiveRecord: 141.6ms)