Refactor util method, improve memory usage