Optimize loops and resize event handler