Thursday, March 24, 2011

getSystemService() calls are nearly free

Random fact of the day: calls to Context.getSystemService(servicename) are close to be free of overhead if they are called multiple times in the same program.

I had a look into the source of the ContextImpl class where mostly code like this is used to return services:

private AlarmManager getAlarmManager() {
synchronized (sSync) {
if (sAlarmManager == null) {
IBinder b = ServiceManager.getService(ALARM_SERVICE);
     IAlarmManager service = IAlarmManager.Stub.asInterface(b);
       sAlarmManager = new AlarmManager(service);
    }
  }
    return sAlarmManager;
}



So it's nearly free to request a systemservice multiple times which comes handy when you need to pass multiple managers around in your program. You don't have to pass them into every class, the context is just enough.

This creates a nice interface for the caller as he doesn't need to know and/or create all the objects you need. All he knows is that you need a Context which enables you to freely change your implementation at any given time without changing your interface.

No comments:

Post a Comment