本文介绍了Marshal.PtrToStringUni()与新的String()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有类型char *来UNI code字符串的指针,我知道的长度:

Suppose i have a pointer of type char* to unicode string, and i know the length:

char* _unmanagedStr;
int _unmanagedStrLength;

和我有2种方式将其转换为.NET字符串:

and i have 2 ways to convert it to .NET string:

Marshal.PtrToStringUni((IntPtr)_unmanagedStr, _unmanagedStrLength);

new string(_unmanagedStr, 0, _unmanagedStrLength);

在我的测试中,无论是电话给了我完全相同的结果,但新的字符串()就像1.8倍倍元帅更快。 PtrToStringUni()

In my tests, both calls gives me exactly the same result, but the new string() is like 1.8x times faster than Marshal.PtrToStringUni().

这是为什么性能差异?有没有之间的另一个功能差异的两个?

Why is that performance difference?Is there any another functional difference between the both?

推荐答案

从可用的源$ C ​​$ C(转子)来看,System.String(字符*)构造函数使用了大量优化$ c到CtorCharPtr $ C路径( ),它分配的字符串FastAllocateString()。 Marshal.PtrToStringUni()如下,它是用C ++完全不同的code路径看起来是复制串两次,没有一个快分配器的好处。

Judging from available source code (Rotor), the System.String(Char*) constructor uses a heavily optimized code path through CtorCharPtr(), it allocates the string with FastAllocateString(). Marshal.PtrToStringUni() follows an entirely different code path, it is written in C++ and looks to be copying the string twice, without the benefit of a "fast allocator".

显然,不一样的程序员在此工作。几乎可以肯定连,因为code同一支球队适应不同的编程模型。在常见的最接近的经理很可能是四个级别了。

Clearly, not the same programmer worked on this. Almost certainly not even the same team since the code fits a different programming model. The closest manager in common was probably four levels up.

不知道如何将是有益的,使用快速之一。硬伤会产生一种类似Windows上的异常。

Not sure how that would be helpful, use the fast one. Mishaps would generate a similar kind of exception on Windows.

这篇关于Marshal.PtrToStringUni()与新的String()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 12:45