Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

android - When should I do certain SQLite operations on another thread(not the main thread)?

My Android application includes an SQLite database with an SQLiteOpenHelper class to help manage it. During application use, the user may perform some operations such as adding/deleting/updating etc on the database.

At some points the size of the operation will be known, like this:

  1. user clicks button to save item
  2. the SQLiteDatabase performs a single insert query
  3. user continues using app

At other areas of the app, the operation may be large, like inserting 10+ items into the database all at once.

Questions:

  • should I thread simple operations like inserting/updating/deleting/viewing 1 item?
  • will it take longer to insert 1 item into a table which contains many items(like 30+) than it would take to insert into a table with no items?
  • if i don't need to thread such simple operations, at what point do you suggest i start threading them?

when i say thread i mean using a thread that is not the main UI thread.

edit: I realize that small operations do not take much time and i could very well get away with doing them on the main thread. I am just concerned that it would be bad practice to be executing them on the main thread and would like clarification!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

General rule for everything: If it's fast enough, do it on the main thread. If not, use a worker thread.

Unless you have a ridiculously huge database, a single operation almost never warrants a separate thread. Databases in general are designed to scale well, but of course a very big database (10,000+ rows?) will be a bit slower than a small one. 30 rows, however, is nothing.

I would start threading stuff if you have a lot of operations going on, like a bunch of queries, or complicated queries that span several tables.

As with everything - profile your app, and if it's too slow, optimize. Don't write an awesome synchronized super-duper multi-core-ready database handler if none of your queries takes longer than 2ms.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...