optimize alogrithm