optimized memory usage. thanks to nneonneo at stackoverflow