将 varbinary 数据从 SQL Server 获取到 C# 字节数组的最快方法是什么?
标题不言而喻。
我正在处理大小接近 2MB 的文件/数据。
The title speaks for itself.
I'm dealing with files/data near 2MB in size.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要数组中的字节,那么所有方法几乎都是相同的,因为您必须将结果流中的所有字节流式传输到数组中(SqlClient 类将为您执行此操作)。
存储过程或数据库表中的字段是否有 varbinary 输出参数并不重要,但存储过程会稍微快一些,因为您没有有关要返回的结果集的架构信息。 然而,与您传回的数据大小相比,这可以忽略不计。
如果您确实想要提高性能,最好使用设置了 SequentialAccess 的 DataReader,然后在读取器上调用 GetBytes 以获取返回的字段。 通过调用此方法,您可以仅提取所需的字节,并且可以分块处理数据。
这很重要,因为尝试分配大小为 2MB 的字节数组时肯定会遇到问题。 一般来说,开始分配大连续的内存块(这就是数组)是一个坏主意,并且会降低性能。 如果可能,以较小的块处理数据。
If you need the bytes in an array, then all the methods are pretty much going to be the same, since you have to stream all the bytes from the result stream into the array (the SqlClient classes are going to do this for you).
It doesn't matter if you have a varbinary output parameter on a stored procedure or a field in a database table, although the stored procedure will be slightly faster since you don't have schema information about a result set to return. This is negligible compared to the size of the data you are shuttling back, however.
If you really want a performance improvement, you are better off using a DataReader with SequentialAccess set and then calling GetBytes on the reader for the field that is returned. By calling this, you pull only the bytes you need and can process the data in chunks.
This is important, because you are definitely going to have issues trying to allocate an array of bytes 2MB in size. Generally speaking, starting to allocate large contiguous blocks of memory (which is what arrays are) is a bad idea, and will kill performance. Where possible, process the data in smaller chunks.
SqlDataReader.GetBytes 应该是什么您正在寻找。
SqlDataReader.GetBytes should be what you're looking for.