我什么时候应该在另一个线程(不是主线程)上执行某些 SQLite 操作? [英] When should I do certain SQLite operations on another thread(not the main thread)?

查看:29
本文介绍了我什么时候应该在另一个线程(不是主线程)上执行某些 SQLite 操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Android 应用程序包含一个带有 SQLiteOpenHelper 类的 SQLite 数据库来帮助管理它.在应用程序使用过程中,用户可能会对数据库进行一些添加/删除/更新等操作.

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. 用户点击按钮保存项目
  2. SQLiteDatabase 执行单个 insert 查询
  3. 用户继续使用应用

在应用程序的其他区域,操作可能会很大,比如一次将 10 多个项目插入数据库.

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

问题:

  • 我应该线程化简单的操作,比如插入/更新/删除/查看 1 个项目吗?
  • 将 1 个项目插入包含许多项目(例如 30+)的表格是否比插入没有项目的表格花费的时间更长?
  • 如果我不需要线程化这么简单的操作,您建议我在什么时候开始线程化它们?
  • 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?

当我说线程时,我的意思是使用一个不是主 UI 线程的线程.

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!

推荐答案

一般规则:如果速度够快,就在主线程上做.如果没有,请使用工作线程.

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

除非你有一个大得离谱的数据库,否则单个操作几乎永远不会保证一个单独的线程.数据库通常被设计为可以很好地扩展,但是当然一个非常大的数据库(10,000+ 行?)会比一个小的数据库慢一点.然而,30 行不算什么.

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.

与所有内容一样 - 分析您的应用,如果速度太慢,请进行优化.如果您的查询都没有超过 2 毫秒,请不要编写很棒的同步超级欺骗多核就绪数据库处理程序.

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.

这篇关于我什么时候应该在另一个线程(不是主线程)上执行某些 SQLite 操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆