Slight performance improvement

test the existence of imported names outside the loop
and make sure they are imported before entering the loop