Pre-compute gradient function to reduce computation overhead

Change-Id: I111ae78f4b71e8f3b95d729da6e1825f00dfe0bf