Performance comparison: AsyncTasks vs Threads

android, android-asynctask

Solution

Can someone throw some light on it. Which one should I use for better performance?

I think if you imagine case when you start once native Thread and AsyncTask i think that performance won't differ.

Usually native threads are used in the case if you don't want to inform potential `USER` with relevant information about progress in some task via `UI`. Here, native threads fail because they are not synchronized with `UI` thread and you cannot perform manipulating with UI from them.

On the other hand, AsyncTask combines background work with UI work and offers methods which are synchronized with UI and allow performing UI updates whenever you want via invoking proper methods of its lifecycle.

Generally if some task lasts more than 5 seconds you should inform `USER` that

"something working on the background, please wait until it will be finished"

For sure, this can be reached with both in different ways but this strongly depends on character of your task - if you need to show progress of task(how much MB is already downloaded, copying number of files and show name of each in progress dialog etc.) or you don't(creating some big data structure in "silent" only with start and end message for instance).

So and at the end of my asnwer:

Which one should I use for better performance?

Completely right answer i think you cannot get because each developer has different experiences, different coding style. How i mentioned, their performance not differ. I think that it's same(if you will read 50 MB file, it won't be faster read neither native thread nor AsyncTask). It depends again on character of task and your personal choice.

Update:

For tasks that can last much longer periods of time, you can try to think also about `API` tools provided by `java.util.concurrent` package(ThreadPoolExecutor, FutureTask etc.)

Problem

In my app, I have to call a method which does some heavy work (I can feel device lagging). To avoid this I created an `AsyncTask` and it works perfectly fine. I implemented the same thing using a `Thread` and here, too, it does not give any hiccup and works fine. Now my question is which one better performance-wise - `AsyncTask` or `Thread`. I know `AsyncTask` uses a threadpool to perform background tasks but in my case it will be called only once. So I don't think it will create any problems. Can someone throw some light on it. Which one should I use for better performance? Note: Both are being called in my Activity e.g. from UI the thread.

Original source

Related problems