Use function outside of loop

Otherwise the function is executed n times which is a lot of overhead.

@MorrisJobke 
Spaces