I suspect that your problem is time, not memory or computing power. I think the PHP process is timing out (on many servers, you only have 30 seconds no matter what). You definitely shouldn't do everything in one bit of code.
Probably, you are right. I find what maximum execution time for Hostmonster is 128 second.