I think you can remove this ifelse. The ifelse have overhead that if much begger then doing the computation of both branch. The easy change is to use T.switch()