我今天早上写了一个快速客户端,当我注意到在后续保存之后,性能会降低时,只是将一堆数据插入到表存储中。
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
为什么性能下降?
答案 0 :(得分:1)
我相信你的测试代码中有一个错误。
for (int x = 0; x < i * 50; x++)
您正在迭代i * 50
次,因此每次通过外部循环,您将比上一次添加50个实体。第一次通过你添加0个实体,确实非常快。那么50,然后是100,然后是150,等等。这是掩盖的,因为你的记录代码每次盲目地增加100个计数,即使这不是你实际添加的数字。你可能想要的是:
for (int x = 0; x < 100; x++)
关于性能分析结果,此代码的大部分内容都适用于内存数据。 SaveChanges()
进行网络通话,这就是它占用时间的原因。
我意识到这是测试代码。但是,如果您实际上尝试将大量实体添加到单个PartitionKey中,则建议使用批处理。