fix bug and improve memory usage and performance