DataSet作内存数据库
少量数据时操作快,不需外部依赖,如sqlite虽然也很好用,但需要不少外部的dll
性能:
初始化代码:
dt = new DataTable("t"); dt.Columns.Add("id"); dt.Columns.Add("msg"); int i = 0; for (; i < 1000000; i++) { dt.Rows.Add(i, Guid.NewGuid().ToString()); dic[i.ToString()] = i.ToString(); } this.textBox1.Text = Guid.NewGuid().ToString(); dt.Rows.Add(i, this.textBox1.Text); dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };
普通查询,100万行,首次查询需5000ms,后续查询都在1ms内,按列msg查询也一样,缺点是第1次很慢:
Stopwatch sw = Stopwatch.StartNew(); DataRow[] drs = dt.Select("id = '600000'"); this.textBox2.Text = drs.Length.ToString(); this.textBox3.Text = sw.Elapsed.TotalMilliseconds.ToString(); sw.Stop();
按字典查询,首次和后续都在1ms内,我以前都这样做,实际上按主键查询即可,这个额外维护了一个字典。
Stopwatch sw = Stopwatch.StartNew(); this.textBox2.Text = dic["60000"]; this.textBox3.Text = sw.Elapsed.TotalMilliseconds.ToString(); sw.Stop();
按主键查询,首次和后续都在1ms内,未找到时返回null。必须要有主键,可以是复合主键
Stopwatch sw = Stopwatch.StartNew(); object[] objs = new object[] { "60000000" }; DataRow dr = dt.Rows.Find(objs); this.textBox2.Text = dr[0].ToString(); this.textBox3.Text = sw.Elapsed.TotalMilliseconds.ToString(); sw.Stop();