Improve code to avoid doing the same computation twice