Is NSTimer expensive?

I use about 20 UIImageView small airplane images (50x50 pixels) making simple animations on the iPhone screen. Animation is performed by shifting the center property of the UIImageView with a timer interval.

 [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] 

What is the best practice: create one NSTimer and loop 20 UIImageView to set the center property when the timer starts? Or should I just create one NSTimer per UIImageView object? NSTimer Resource NSTimer ?

+5
source share
3 answers

I don't think the resource is intense, but common sense seems to dictate that using 1 timer is probably better than 20.

It looks like your timer is set to fire 100 times per second, which seems a bit overkill. Do you revive every sprite every time the timer fires? You might want to try shooting 20-30 times per second instead (or maybe even less).

You might also want to look at the built-in animation features. It looks like they are likely to work very well for what you do.

+4
source

you can try both options and use the built-in profiling tools that come with Xcode to measure resource usage.

+3
source

Timers are actually quite expensive, energetically.

Every nanosecond during which the OS (or the applications running on it) do nothing, the CPU does not work in one of several low-power modes. Exiting a system from an idle state entails energy costs when the CPU and other systems exit a state of low power consumption. If the timer causes the system to wake up, it carries that cost. The more often the timer fires, the higher the cost of energy. On mobile devices, this can significantly affect battery life.

In this sense, it’s much more efficient to wake up the system once, do all the work, and then let it sleep as much as possible. Returning to your example, if you profile this, it will be more efficient to use 1 timer rather than 20 timers, each of which is triggered 100 times per second.

Later versions of the OS allow you to specify the tolerance (in%). This allows the system to group timers and run them at the same event in order to save energy. It seems that what you are doing is not time critical (in the sense of real-time execution), so allowing clearance (e.g. 10%) should help.

Example: [myTimer setTolerace:0.3];

More on timer tolerance here: https://developer.apple.com/documentation/foundation/nstimer

0
source

All Articles