Performance improvements and cleanup

* fixed some scope issues (e.g. `i` wasn’t defined)
* added some missing semicolons
* prevented function from being created in a loop
* proper invocation of constructors
* improve the performance of frequently called functions/loops
* Clean up memory leaks and reduces the overall memory footprint. There were anywhere from 3-5 listeners per chunk that were being leaked.