Android Application Performance

I'm curious about performance and CPU / ram requirements for two different runnables startup methods

I have a code that collects sensor data every 10 ms and inserts values ​​into a database in a background thread (using one thread executor). The contractor service is created as follows:

executor = Executors.newSingleThreadExecutor();

One way to do this 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 textbooks, but since I do it every 10 ms, it feels resource-intensive when I create a new object every time a change in sensor value is detected. Is this new object just redefined every 10 ms? Or does it take up more RAM when creating new objects?

Since then, I updated 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 only instantiate one object at a time, instead of doing it every time the sensors change. Am I right in thinking that this has lower RAM usage than the previous method? Is there a more efficient / better way to accomplish this task?

+4
source share
1 answer

Creating a new Runnable instance every 10 ms will likely cause the garbage collector more often and may affect the performance of your application. Your second approach, in my opinion, is much better.

+1
source

Source: https://habr.com/ru/post/1246402/


All Articles