The problem of huge tree created by looping is solved in my product Tabbydb from KwikQuery.
Please refer to KwikQuery llc
There is a sample note book button where you can compare the perf difference in realtime.