memory optimizations and code refactoring
small optimization