C++/CLI 性能与本机 C++ 相比?
早上好,
我正在编写一个拼写检查器,就本例而言,它对性能至关重要。也就是说,由于我计划连接到数据库并使用 C# 制作 GUI,因此我用 C 编写了一个编辑距离计算例程,并编译为一个 DLL,我使用 DllImport
在 C# 中使用该 DLL。问题是,我认为(尽管我可能是错的)将单词从 String
逐一编组到 char *
会导致很多开销。也就是说,我考虑使用 C++/CLI,以便可以直接使用 .NET 中的 String
类型...我的问题是 C++/CLI 性能与本机 C 代码相比如何进行繁重的工作数学计算和数组访问?
非常感谢。
Good morning,
I am writting a spell checker which, for the case, is performance-critical. That being, and since I am planning to connect to a DB and making the GUI using C#, I wrote an edit-distance calculation routine in C and compiled to a DLL which I use in C# using DllImport
. The problem is that I think (though I am possibly wrong) that marshalling words one by one from String
to char *
is causing a lot of overhead. That being, I thought about using C++/CLI so that I can work with the String
type in .NET directly... My question is then how does C++/CLI performance compares to native C code for heavy mathematical calculations and array access?
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++/CLI 也必须进行某种形式的编组。
与所有与性能相关的问题一样,您应该测量并优化。您确定 C# 的速度不足以满足您的目的吗?不要低估 JIT 编译器将要做的优化。不要在没有尝试的情况下仅仅为了管理而猜测语言实现的开销。如果这还不够,您在尝试非托管代码之前是否考虑过不安全的 C# 代码(带有指针)?
关于 C++/CLI 的性能概况,它实际上取决于它的使用方式。如果使用 (
/clr:pure
) 编译为托管代码 (CIL),它与 C# 不会有太大不同。 C++/CLI 中的本机 C++ 函数将具有与普通 C++ 类似的性能特征。在本机 C++ 和 CLI 环境之间传递对象会产生一些开销。C++/CLI will have to do some kind of marshaling too.
Like all performance related problems, you should measure and optimize. Are you sure C# is not going to be fast enough for your purposes? Don't underestimate the optimizations that JIT compiler is going to do. Don't speculate on the overhead of a language implementation solely for being managed without trying. If it's not enough, have you considered unsafe C# code (with pointers) before trying unmanaged code?
Regarding the performance profile of C++/CLI, it really depends on the way it's used. If you compile to managed code (CIL) with (
/clr:pure
), it's not going to be very different from C#. Native C++ functions in C++/CLI will have similar performance characteristics to plain C++. Passing objects between native C++ and CLI environment will have some overhead.我没想到瓶颈会出现在 DLLImport 上。
我编写过每秒调用 DLLImport 数百次的程序,它工作得很好。
您将支付少量的性能罚款,但罚款很小。
I would not expect that the bottleneck will be with the DLLImport.
I have written programs which call DLLImport several hundert times per second and it just works fine.
You will pay a small performance fine, but the fine is small.
不要假设您知道需要优化哪些内容。让抽样告诉你。
我做了几个拼写校正器,以及我的做法(此处概述)是将字典组织为内存中的字典树,并对其进行搜索。
如果单词数量很大,可以通过共享公共后缀来大大减小 trie 的大小。
Don't assume you know what needs to be optimized. Let sampling tell you.
I've done a couple spelling-correctors, and the way I did it (outlined here) was to organize the dictionary as a trie in memory, and search upon that.
If the number of words is large, the size of the trie can be much reduced by sharing common suffixes.