I'm wondering about performance and cpu/ram requirements for 2 different methods of starting runnables
I have some code that collects sensor data every 10ms and inserts the values into a database on a background thread (using a single thread executor). Executor service is created as follows:
executor = Executors.newSingleThreadExecutor();
One way to do that would be something like...
public void onSensorChanged(SensorEvent event) {
//get sensor values
//insert into database
executor.execute(new Runnable(){
//database insert code here
});
}
I see this method a lot in tutorials, but because I'm doing this every 10ms, it feels resource intensive as I'm creating a new object every single time a sensor value change is detected. Does this new object just get overridden every 10ms? Or is it taking up increasing amounts of RAM as new objects are created?
I have since refactored my code to look more like this:
executor = Executors.newSingleThreadExecutor();
myRunnable = new MyRunnable();
class MyRunnable implements Runnable {
public void run() {
//database insert code here
}
}
public void onSensorChanged(SensorEvent event) {
//get sensor values
//insert into database
executor.execute(myRunnable);
}
My thinking is that I instantiate only a single object once, instead of doing it every time sensors change. Am I correct in thinking this has lower RAM usage than the previous method? Is there a more efficient/better way to accomplish this task?
Creating new Runnable
instance every 10 ms will surely cause garbage collector to kick in more often and may impact your application performance. Your second approach i think is much better.
来源:https://stackoverflow.com/questions/36395440/android-thread-runnable-performance