为什么我从来没有使用不安全的块来修改字符串? [英] Why should I never use an unsafe block to modify a string?

查看:135
本文介绍了为什么我从来没有使用不安全的块来修改字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个,我想以某种方式修改字符串。例如:扭转这种局面或upcase它。

I have a String which I would like to modify in some way. For example: reverse it or upcase it.

我发现,这样做的最快方法是使用不安全的块的指针。

I have discovered that the fastest way to do this is by using a unsafe block and pointers.

例如:

        unsafe 
        {
            fixed (char* str = text)
            {
                *str = 'X';
            }
        }

有什么原因,我永远也不会做到这一点?

Are there any reasons why I should never ever do this?

推荐答案

在.NET框架要求的字符串是不可变的。由于这一要求它能够优化各种操作。

The .Net framework requires strings to be immutable. Due to this requirement it is able to optimise all sorts of operations.

字符串实习是这个要求一个高杠杆很好的例子。要加快一些字符串比较(和减少内存消耗).net框架保持指针的意思,所有的pre定义的字符串将生活在这本字典或您拨打字符串任何字符串。实习生方法上。当IL指令ldstr被称为它将检查拘禁字典和避免内存分配,如果我们已经串分配,注意:的 String.Concat 不会检查实习字符串。

String interning is one great example of this requirement is leveraged heavily. To speed up some string comparisons (and reduce memory consumption) the .Net framework maintains a Dictionary of pointers, all pre-defined strings will live in this dictionary or any strings where you call the String.intern method on. When the IL instruction ldstr is called it will check the interned dictionary and avoid memory allocation if we already have the string allocated, note: String.Concat will not check for interned strings.

.NET框架的这种特性意味着,如果你开始摆弄字符串直接左右你可能会损坏你的实习表,进而破坏其他引用相同的字符串。

This property of the .net framework means that if you start mucking around directly with strings you can corrupt your intern table and in turn corrupt other references to the same string.

例如:

         // 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

这篇关于为什么我从来没有使用不安全的块来修改字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆