If you do take the function approach, make sure to cache the result in a local variable rather than making the call multiple times as there is a lot of overhead to function calls. Looking over your code it looks like there could be several opportunities to optimize by caching in local variables.