将 varbinary 数据从 SQL Server 获取到 C# 字节数组的最快方法是什么?

发布于 2024-07-16 21:07:32 字数 46 浏览 1 评论 0原文

标题不言而喻。

我正在处理大小接近 2MB 的文件/数据。

The title speaks for itself.

I'm dealing with files/data near 2MB in size.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜无邪 2024-07-23 21:07:32

如果您需要数组中的字节,那么所有方法几乎都是相同的,因为您必须将结果流中的所有字节流式传输到数组中(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.

鲸落 2024-07-23 21:07:32

SqlDataReader.GetBytes 应该是什么您正在寻找。

SqlDataReader.GetBytes should be what you're looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文