Optimization for applying palette
Fix memory leak