我有一个字符串,我想以某种方式修改它。例如:反转或大写。
我发现最快的方法是使用不安全的块和指针。
例如:
unsafe
{
fixed (char* str = text)
{
*str = 'X';
}
}
有什么理由让我永远不应该这样做吗?
.Net 框架要求字符串是不可变的。由于这一要求,它能够优化各种操作。
字符串实习 http://en.wikipedia.org/wiki/String_intern_pool这是这一要求被大量利用的一个很好的例子。为了加速某些字符串比较(并减少内存消耗),.Net 框架维护一个指针字典,所有预定义的字符串都将存在于该字典或您调用的任何字符串中。String.intern
方法上。当调用 IL 指令 ldstr 时,如果我们已经分配了字符串,它将检查 interned 字典并避免内存分配,请注意:字符串连接 http://bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx不会检查实习字符串。
.net 框架的这一属性意味着,如果您开始直接使用字符串进行处理,则可能会损坏您的实习表,进而损坏对同一字符串的其他引用。
例如:
// these strings get interned
string hello = "hello";
string hello2 = "hello";
string helloworld, helloworld2;
helloworld = hello;
helloworld += " world";
helloworld2 = hello;
helloworld2 += " world";
unsafe
{
// very bad, this changes an interned string which affects
// all app domains.
fixed (char* str = hello2)
{
*str = 'X';
}
fixed (char* str = helloworld2)
{
*str = 'X';
}
}
Console.WriteLine("hello = {0} , hello2 = {1}", hello, hello2);
// output: hello = Xello , hello2 = Xello
Console.WriteLine("helloworld = {0} , helloworld2 = {1}", helloworld, helloworld2);
// output : helloworld = hello world , helloworld2 = Xello world
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)