今天早上我正在编写一个快速客户端,只是将一堆数据插入到表存储中,当我注意到后续保存后,性能会下降。
public class MyObject : TableServiceEntity
{
public MyObject()
{
this.RowKey = Guid.NewGuid().ToString();
}
public string SomeProperty { get; set; }
}
然后我有一个简单的代码块来添加一些数据......
Stopwatch timer = new Stopwatch();
for (int i = 0; i < target / 50; i++)
{
CloudTableClient client = account.CreateCloudTableClient();
client.CreateTableIfNotExist(entitySet);
TableServiceContext context = client.GetDataServiceContext();
timer.Reset();
timer.Start();
for (int x = 0; x < i * 50; x++)
{
var obj = new MyObject();
context.AddObject(entitySet, obj);
context.SaveChanges();
}
total += 100;
timer.Stop();
Console.WriteLine("Added 100 entities in {0} seconds; total: {1}", timer.Elapsed.Seconds, total);
}
这是我在运行时看到的(控制台应用程序)
Added 100 entities in 0 seconds; total: 100
Added 100 entities in 0 seconds; total: 200
Added 100 entities in 1 seconds; total: 300
Added 100 entities in 2 seconds; total: 400
Added 100 entities in 4 seconds; total: 500
Added 100 entities in 4 seconds; total: 600
Added 100 entities in 6 seconds; total: 700
Added 100 entities in 6 seconds; total: 800
为什么性能会下降?
- 如果我将上下文、客户端和/或帐户移出循环,它不会改变
- 实施context.ResolveType没有解决问题
- 分析之后,context.SaveChanges 方法是瓶颈所在
- 重新运行应用程序会重现相同的结果;即使数据库中有成百上千的其他实体。