1

When my loop runs for about 15k times too much memory is consumed. It's even going beyond 1 GB. What I am doing inside the loop is a series of Core data entity updating/creation. Is there any way I could control the memory usage?

Advaith
  • 1,087
  • 3
  • 12
  • 31

2 Answers2

2

Yes, you should use autorelease pools inside your loop. Here is the official Apple note about this, and if you use ARC in your project, this answer will be helpful.

Community
  • 1
  • 1
dmirkitanov
  • 1,396
  • 1
  • 12
  • 29
  • Cool! It really worked out. The memory is not shooting up beyond 60 MB!!! Thank you very much for the feedback :) But one more issue, I can hear some noise indicating that CPU is being used badly while executing the loop. What's the best way to reduce the CPU usage in such a case? – Advaith Aug 06 '12 at 10:55
  • Advaith, provided that your loop runs in a secondary thread, you could use something like [NSThread sleepForTimeInterval: 0.025] to throttle - do the math though, as 0.025s*15000 = 375s. See also: http://stackoverflow.com/questions/6785069/get-cpu-percent-usage – magma Aug 06 '12 at 11:03
  • To reduce the CPU usage I would advice using NSOperation on low priority queues. So, basically, you need to move your import operation into NSOperation class, and before putting your operation onto NSOperationQueue, set its priority by this method: setQueuePriority:NSOperationQueuePriorityVeryLow. Don't forget to read this very important article (http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/coredata/Articles/cdConcurrency.html) about CoreData and concurrency. Hope it will help. – dmirkitanov Aug 06 '12 at 11:24
  • Hmmm.. I tried both these methods. But it's not reducing the usage much – Advaith Aug 06 '12 at 12:39
  • I'd rather agree with Paul's comment on your [question](http://stackoverflow.com/questions/11828567/cpu-usage-shooting-up-when-i-am-running-a-for-in-loop-os-x-app), maybe just ignore that and let mac/iphone do their job :) – dmirkitanov Aug 06 '12 at 13:08
1

Wrap the content of your loop with an autorelease pool and drain it from time to time.

JustSid
  • 25,168
  • 7
  • 79
  • 97