What are the upfront fees incurred by taking out of the 401k? Is that 5% a fee or interest that you pay back to yourself (into the 401k)?
This is one of the few times it may makes sense, so that you are paying yourself interest instead of the bank. You will still lose out mathematically to investing, but it is close enough that it may be worth it (to you)
HOWEVER: Some things to consider:
1) If you have a job loss, the 401k repayment becomes due immediately or pay the fine. Thats expensive.
2) Student loans, as crappy as they are, have some pretty good repayment flexibility in an emergency. You could easily buy yourself a few months without too much expense in a job loss. Compared to the (drastic) repayment requirements of a 401k loan, the student loans are downright generous.
3) How quickly could you pay off the student loans without the 401k loan
4) how quickly could you pay off the 401k loan.
Overall, there is a ton of risk and you lose mathematically by doing this in the average scenario, but it is an interesting idea.