How to optimize the following code?

Awesome! Thank you all for the nice suggestions!