sqlite采用UUID主键和int型自增主键性能对比测试

前端之家收集整理的这篇文章主要介绍了sqlite采用UUID主键和int型自增主键性能对比测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


最近在工作中,遇到到了sqlite主键类型选择的问题,于是就做个测试程序来测试sqlite采用UUID主键和int型自增主键性能对比。(本人时间有限,没有做多次测试,希望有人能帮着多测试一下)

1.sqlite采用UUID主键的优点和缺点。

优点:安卓端sqlite表的主键和服务器端数据库表的主键可以保持一致,不用做复杂的业务处理,开发效率高;数据安全性较好,用户无法从id估算该表的数据量。
缺点:UUID字符串长度太长,加大网络数据传输数据量。

2.sqlite采用int型自增主键的优点和缺点。

优点:int型主键字符串长度短,网络传输数据量不大。
缺点:安卓端sqlite表的主键与服务器端数据库表的主键不可能一致,需要做复杂的业务处理,开发效率低;做表关联需要insert后返回主键值的时候需要多一次select max(id)的操作。

3.测试环境

测试手机 三星Galaxy S3(i9300)
安卓版本 Android 4.3 (CM10.2)
软件环境 已ROOT,杀掉全部后台服务
测试用例sqlite表结构
UUID主键:
[sql]
  1. createtablesysUserUUID(idTEXTPRIMARYKEY,uNameTEXT)
int自增主键:
[sql]
  1. createtablesysUserInt(idINTEGERPRIMARYKEYAUTOINCREMENT,uNameTEXT)

转换json工具包:gson-2.2.4.jar

4.测试结果

操作 UUID主键 int自增主键
插入数据耗时 100条 1582ms 1583ms
500条 10308ms 9496ms
读取数据耗时 100条 19ms 25ms
500条 58ms 59ms
json字符串大小 100条 6.14kb 2.62kb
500条 31.14kb 13.95kb


5. 结论

根据测试数据我们可以得出以下结论:
1.sqlite只是简单的文件数据库,没有对任何类型的主键进行优化,所以采用UUID和int自增主键没有本质上的性能差距,而我们测试中UUID比int主键稍微慢一点的原因我认为是uuid字符串太长。
2.用json传输数据时,每100条uuid的数据会比int型的大3.4kb左右,考虑到本测试中int型主键都是从1开始的,而实际应用中可能大于10000,故而他们的差距应该比3.4kb要小;如果再考虑做表关联时需要传输复合主键,那么int型的大小应该再大一些。考虑到一般读取数据不会超过100条,这个差距即使在2G的网络环境下对响应时间的影响也不到0.5秒。故而数据大小的区别可以忽略。

6. 附:主要测试类

[java]
  1. packagecom.zf.uuidtest;
  2. importjava.io.File;
  3. importjava.util.ArrayList;
  4. importjava.util.Date;
  5. importjava.util.List;
  6. importjava.util.UUID;
  7. importjavax.crypto.interfaces.PBEKey;
  8. importcom.example.uuidtest.R;
  9. importcom.google.gson.Gson;
  10. importandroid.os.Bundle;
  11. importandroid.os.Environment;
  12. importandroid.os.Handler;
  13. importandroid.app.Activity;
  14. importandroid.app.ProgressDialog;
  15. importandroid.database.Cursor;
  16. importandroid.database.sqlite.sqliteDatabase;
  17. importandroid.database.sqlite.sqliteOpenHelper;
  18. importandroid.util.Log;
  19. importandroid.view.Menu;
  20. importandroid.view.View;
  21. importandroid.view.View.OnClickListener;
  22. importandroid.widget.Button;
  23. importandroid.widget.EditText;
  24. importandroid.widget.ProgressBar;
  25. importandroid.widget.TextView;
  26. importandroid.widget.Toast;
  27. publicclassMainActivityextendsActivity{
  28. TextViewtvUUIDTitle;
  29. TextViewtvIntTitle;
  30. EditTextetTestIntCount;
  31. EditTextetTestUUIDCount;
  32. ButtonbtnStartTestUUID;
  33. ButtonbtnStartTestInt;
  34. TextViewtvUUIDRs;
  35. TextViewtvIntRs;
  36. ProgressBarpbInProgress;
  37. ButtonbtnStartLoadTestUUID;
  38. ButtonbtnStartLoadTestInt;
  39. intintTestCnt;
  40. intUUIDTestCnt;
  41. longintTestCost;
  42. longUUIDTestCost;
  43. FileUUIDFile;
  44. FileintFile;
  45. DatabaseUtildb;
  46. staticfinalintTEST_INT_MSG=11110;
  47. staticfinalintLOAD_INT_MSG=41110;
  48. staticfinalintTEST_UUID_MSG=11111;
  49. staticfinalintLOAD_UUID_MSG=41111;
  50. staticfinalintDONE_CNT_MSG=21111;
  51. staticStringAPP_DIR="test_sqlite";
  52. intdoneCnt;
  53. List<SysUserUUID>sysUserUUIDs;
  54. List<SysUserInt>sysUserInts;
  55. @Override
  56. protectedvoidonCreate(BundlesavedInstanceState){
  57. super.onCreate(savedInstanceState);
  58. setContentView(R.layout.activity_main);
  59. db=newDatabaseUtil(this);
  60. db=db.open();
  61. db.executesql("droptableifexistssysUserInt");
  62. db.executesql("droptableifexistssysUserUUID");
  63. db.executesql("createtablesysUserInt(idINTEGERPRIMARYKEYAUTOINCREMENT,uNameTEXT)");
  64. db.executesql("createtablesysUserUUID(idTEXTPRIMARYKEY,uNameTEXT)");
  65. initView();
  66. }
  67. Handlerhandler=newHandler(){
  68. publicvoidhandleMessage(android.os.Messagemsg){
  69. pbInProgress.setVisibility(View.GONE);
  70. switch(msg.what){
  71. caseDONE_CNT_MSG:
  72. break;
  73. caseTEST_INT_MSG:
  74. StringintRs="插入耗时"+intTestCost+"ms";
  75. tvIntRs.setText(intRs);
  76. btnStartLoadTestInt.setEnabled(true);
  77. break;
  78. caseTEST_UUID_MSG:
  79. StringuuidRs="插入耗时"+UUIDTestCost+"ms";
  80. tvUUIDRs.setText(uuidRs);
  81. btnStartLoadTestUUID.setEnabled(true);
  82. break;
  83. caseLOAD_INT_MSG:
  84. Stringrs1=tvIntRs.getText().toString()+",读取耗时"
  85. +intLoadCost+"ms,json文件大小"+FileUtils.getFormatSize(intFile.length());
  86. tvIntRs.setText(rs1);
  87. break;
  88. caseLOAD_UUID_MSG:
  89. Stringrs=tvUUIDRs.getText().toString()+",读取耗时"
  90. +UUIDLoadCost+"ms,json文件大小"+FileUtils.getFormatSize(UUIDFile.length());
  91. tvUUIDRs.setText(rs);
  92. break;
  93. default:
  94. break;
  95. }
  96. };
  97. };
  98. voidinitView(){
  99. tvUUIDTitle=(TextView)findViewById(R.id.tvUUIDTitle);
  100. tvIntTitle=(TextView)findViewById(R.id.tvIntTitle);
  101. etTestIntCount=(EditText)findViewById(R.id.etTestIntCount);
  102. etTestUUIDCount=(EditText)findViewById(R.id.etTestUUIDCount);
  103. tvUUIDRs=(TextView)findViewById(R.id.tvUUIDRs);
  104. tvIntRs=(TextView)findViewById(R.id.tvIntRs);
  105. btnStartTestUUID=(Button)findViewById(R.id.btnStartTestUUID);
  106. btnStartTestInt=(Button)findViewById(R.id.btnStartTestInt);
  107. btnStartLoadTestUUID=(Button)findViewById(R.id.btnStartLoadTestUUID);
  108. btnStartLoadTestInt=(Button)findViewById(R.id.btnStartLoadTestInt);
  109. pbInProgress=(ProgressBar)findViewById(R.id.pbInProgress);
  110. btnStartTestInt.setOnClickListener(newOnClickListener(){
  111. @Override
  112. publicvoidonClick(Viewv){
  113. pbInProgress.setVisibility(View.VISIBLE);
  114. intTestCnt=Integer.parseInt(etTestIntCount.getText()
  115. .toString());
  116. newThread(){
  117. publicvoidrun(){
  118. try{
  119. longstart=newDate().getTime();
  120. for(inti=0;i<intTestCnt;i++){
  121. StringBuildersb=newStringBuilder(
  122. "insertintosysUserInt(uName)values('")
  123. .append("name").append(i).append("')");
  124. db.executesql(sb.toString());
  125. }
  126. longend=newDate().getTime();
  127. intTestCost=end-start;
  128. handler.sendEmptyMessage(TEST_INT_MSG);
  129. }catch(Exceptionex){
  130. ex.printStackTrace();
  131. }
  132. };
  133. }.start();
  134. }
  135. });
  136. btnStartTestUUID.setOnClickListener(newOnClickListener(){
  137. @Override
  138. publicvoidonClick(Viewv){
  139. pbInProgress.setVisibility(View.VISIBLE);
  140. UUIDTestCnt=Integer.parseInt(etTestUUIDCount.getText()
  141. .toString());
  142. newThread(){
  143. publicvoidrun(){
  144. try{
  145. longstart=newDate().getTime();
  146. for(inti=0;i<UUIDTestCnt;i++){
  147. StringBuildersb=newStringBuilder(
  148. "insertintosysUserUUID(id,uName)values('")
  149. .append(UUID.randomUUID())
  150. .append("','").append("name").append(i)
  151. .append("')");
  152. db.executesql(sb.toString());
  153. }
  154. longend=newDate().getTime();
  155. UUIDTestCost=end-start;
  156. handler.sendEmptyMessage(TEST_UUID_MSG);
  157. }catch(Exceptionex){
  158. ex.printStackTrace();
  159. }
  160. };
  161. }.start();
  162. }
  163. });
  164. btnStartLoadTestUUID.setOnClickListener(newOnClickListener(){
  165. @Override
  166. publicvoidonClick(Viewarg0){
  167. pbInProgress.setVisibility(View.VISIBLE);
  168. UUIDTestCnt=Integer.parseInt(etTestUUIDCount.getText()
  169. .toString());
  170. newThread(){
  171. publicvoidrun(){
  172. try{
  173. longstart=newDate().getTime();
  174. Stringsql="select*fromsysUserUUIDorderbyidlimit"
  175. +UUIDTestCnt+"offset0";
  176. Cursorcr=db.mDb.query("sysUserUUID",
  177. newString[]{"id","uName"},null,
  178. null,"idlimit"+UUIDTestCnt
  179. +"offset0");
  180. sysUserUUIDs=newArrayList<SysUserUUID>();
  181. while(cr.moveToNext()){
  182. SysUserUUIDsysUserUUID=newSysUserUUID();
  183. sysUserUUID.setId(cr.getString(0));
  184. sysUserUUID.setuName(cr.getString(1));
  185. sysUserUUIDs.add(sysUserUUID);
  186. }
  187. if(Environment.getExternalStorageState().equals(
  188. Environment.MEDIA_MOUNTED)){
  189. StringdirStr=Environment
  190. .getExternalStorageDirectory()
  191. .getPath()
  192. +File.separator+APP_DIR;
  193. UUIDFile=newFile(dirStr+File.separator
  194. +"uuid.json");
  195. if(!UUIDFile.exists()){
  196. Filedir=newFile(UUIDFile.getParent());
  197. dir.mkdirs();
  198. UUIDFile.createNewFile();
  199. }
  200. Gsongson=newGson();
  201. FileUtils.writeFile(UUIDFile,
  202. gson.toJson(sysUserUUIDs).toString());
  203. }else{
  204. Toast.makeText(MainActivity.this,"sd卡错误",1)
  205. .show();
  206. }
  207. longend=newDate().getTime();
  208. UUIDLoadCost=end-start;
  209. handler.sendEmptyMessage(LOAD_UUID_MSG);
  210. }catch(Exceptione){
  211. e.printStackTrace();
  212. }
  213. };
  214. }.start();
  215. }
  216. });
  217. btnStartLoadTestInt.setOnClickListener(newOnClickListener(){
  218. @Override
  219. publicvoidonClick(Viewarg0){
  220. pbInProgress.setVisibility(View.VISIBLE);
  221. intTestCnt=Integer.parseInt(etTestIntCount.getText()
  222. .toString());
  223. newThread(){
  224. publicvoidrun(){
  225. try{
  226. longstart=newDate().getTime();
  227. Stringsql="select*fromsysUserIntorderbyidlimit"
  228. +intTestCnt+"offset0";
  229. Cursorcr=db.mDb.query("sysUserInt","idlimit"+intTestCnt
  230. +"offset0");
  231. sysUserInts=newArrayList<SysUserInt>();
  232. while(cr.moveToNext()){
  233. SysUserIntsysUserInt=newSysUserInt();
  234. sysUserInt.setId(cr.getInt(0));
  235. sysUserInt.setuName(cr.getString(1));
  236. sysUserInts.add(sysUserInt);
  237. }
  238. if(Environment.getExternalStorageState().equals(
  239. Environment.MEDIA_MOUNTED)){
  240. StringdirStr=Environment
  241. .getExternalStorageDirectory()
  242. .getPath()
  243. +File.separator+APP_DIR;
  244. intFile=newFile(dirStr+File.separator
  245. +"int.json");
  246. if(!intFile.exists()){
  247. Filedir=newFile(intFile.getParent());
  248. dir.mkdirs();
  249. intFile.createNewFile();
  250. }
  251. Gsongson=newGson();
  252. FileUtils.writeFile(intFile,
  253. gson.toJson(sysUserInts).toString());
  254. }else{
  255. Toast.makeText(MainActivity.this,1)
  256. .show();
  257. }
  258. longend=newDate().getTime();
  259. intLoadCost=end-start;
  260. handler.sendEmptyMessage(LOAD_INT_MSG);
  261. }catch(Exceptione){
  262. e.printStackTrace();
  263. }
  264. };
  265. }.start();
  266. }
  267. });
  268. }
  269. longUUIDLoadCost;
  270. longintLoadCost;
  271. voidtestIntId(){
  272. }
  273. voidtestUUIDId(){
  274. }
  275. }
原文链接:https://www.f2er.com/sqlite/199289.html

猜你在找的Sqlite相关文章