If you set your cache limits to high (i.e., too high) and do what you do, it would be wise to get the symptoms you report. If you look at the /sitecore/admin/cache.aspx page while your script is running, this will be shown. I would like the master[items] and master[data] records to keep rising ...
If this case, just setting a lower cache limit would mean that the caches are lowered as needed, which seems like a healthier way to keep things under control.
In addition, if you want to significantly speed up the creation of program elements, try using
using (new BulkUpdateContext()) { code.. }
BulkUpdateContext () may also skip adding items to the cache - I have not checked if this is the case, but if so, it will also most likely fix the memory problem.
(also see this SO answer ). Note that it disables multiple pipelines.
source share