If, as many have suggested, you can do both then do. If you have to make a choice (e.g., if your money would be tied up in the ESPP too long for you to do both), here is one way to evaluate:
P = Pre-tax amount, $
i = investment return
n = years
t1 = current tax rate. Also assumed to be the tax rate when the 401k is withdrawn....
t2 = tax rate on ESPP returns. Note that this is irrespective of whether the money is left in the original stock or moved to another investment.
d = ESPP discount
401k value = P*(1+i)^n*(1-t1). This is the usual formula for compounded returns from an investment which is taxed on withdrawal.
ESPP value = P*(1-t1)/(1-d)*(1-d*t1)*(1+i)^n*(1-t2). Let's take this in pieces:
P*(1-t1) = amount investable after tax
P*(1-t1)/(1-d) = value of stock purchased
P*(1-t1)/(1-d)*(1-d*t1) = amount remaining after taxes are paid on the ordinary income from the ESPP purchase. Note: this is the ESPP I'm familiar with - seattlecyclone may provide a different formula for another type of ESPP.
P*(1-t1)/(1-d)*(1-d*t1)*(1+i)^n*(1-t2) = The usual formula for compounded returns from an investment which is taxed on withdrawal.
Divide the 401k equation by the ESPP equation to get (note that P, i, and n are irrelevant):
(1 - d) / ((1 - d*t1) * (1 - t2))
For values
d = 15%
t1 = 25%
t2 = 15%
the 401k route is ~4% better.
As always, different assumptions may lead to different results. Aka YMMV.