Optimized nnCostFunction (~1.3x faster)