Running it directly lead to the same result, out of memory.
Is it really the delete operation that causes OOM? That’d be rather unusual, so feel free to give me more details.
If it’s the subsequent insert that causes the troubles, could you possibly give us some details on the size of the database after the optimize call? Did you try to fully optimize the database (…using the ALL flag or db:optimize($db, true())…)?