枚举器的 SQL Select 优化
如何针对枚举器优化此查询:
SELECT * FROM Customers
Table Customers
customerId int - has index on it
customerName, etc
返回一组客户的 SqlReader 将以枚举器方式按需读取。虽然它可以返回可以在 foreach 循环中缓慢读取/消耗的巨大数据集,但同一个表上的每个其他查询都会遇到很多争用。如何优化/避免这种情况?游标或选择临时表?
这是一个会引起很多争论的代码示例(我对其进行了分析,数字看起来确实很糟糕):
public void DumpCustomers()
{
Thread thread = new Thread(AccessCustomers);
thread.Start();
// GetCustomers returns enumerator with yield return; big # of customers
foreach (Customer customer in GetCustomers())
{
Console.WriteLine(customer.CustomerName);
System.Threading.Thread.Sleep(200);
}
thread.Abort();
}
public void AccessCustomers()
{
while (true)
{
Console.WriteLine(GetCustomer("Zoidberg").CustomerName);
Thread.Sleep(100);
}
}
PS 我还需要在 MySQL 中对此进行优化。
How can this query be optimized for enumerators:
SELECT * FROM Customers
Table Customers
customerId int - has index on it
customerName, etc
SqlReader that returns a set customers will be read on-demand in an enumerator fashion. While it can return huge datasets that can be read/consumed slowly in a foreach loop, every other query on the same table will encounter a lot of contentions. How can this be optimized/avoided? Cursors or selecting into temp tables?
Here is a code example that will cause a lot of contentions (I profiled it and the numbers look bad indeed):
public void DumpCustomers()
{
Thread thread = new Thread(AccessCustomers);
thread.Start();
// GetCustomers returns enumerator with yield return; big # of customers
foreach (Customer customer in GetCustomers())
{
Console.WriteLine(customer.CustomerName);
System.Threading.Thread.Sleep(200);
}
thread.Abort();
}
public void AccessCustomers()
{
while (true)
{
Console.WriteLine(GetCustomer("Zoidberg").CustomerName);
Thread.Sleep(100);
}
}
P.S. I will also need to optimize this in MySQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1)您是否需要“*”不能指定列。
2) 使用多部分名称 dbo.tablename.fieldname - 这会加快速度
3) 尝试使用 (nolock) 或 (readpast) 进行锁定提示
4) IO 配置文件是什么? SQL每次运行时都必须从磁盘中提取数据吗?
5) 您是否发现服务器上的一个核心已达到最大状态,而另一个核心则处于空闲状态?
6)缓存它!直到您知道发生了更改 - 然后重新加载它。
我已经没有想法了..
1) Do you need the '*' cant you specify the columns.
2) Use multi-part names dbo.tablename.fieldname - this speeds it up
3) try a locking hint with (nolock) or (readpast)
4) Whats the IO profile? Does SQL have to pull the data from disk every time it runs?
5) Do you find one of the cores on your server max out while the other one is idle?
6) Cache it! Until you know there has been a change- then reload it.
I've run out of ideas..