speed optimization

speed optimization be rearanging code and reusing calculation results