当净获得子,并在新的字符串引用相同的原始字符串数据还是数据被复制? [英] When getting substring in .Net, does the new string reference the same original string data or does the data get copied?

查看:98
本文介绍了当净获得子,并在新的字符串引用相同的原始字符串数据还是数据被复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下字符串:

string str1 = "Hello World!";  
string str2 = str1.SubString(6, 5); // "World"



我希望,在上面的例子中 STR2 不复制世界,只是最终被指向只知道它与6的偏移量和长度为5启动相同的内存空间的新字符串。

I am hoping that in the above example str2 does not copy "World", but simply ends up being a new string that points to the same memory space only that it starts with an offset of 6 and a length of 5.

在实际上我处理一些潜在的非常长的字符串,并有兴趣在如何工作的场景表现背后的原因。我与IL不熟悉enaugh寻找到这一点。

In actuality I am dealing with some potentially very long strings and am interested in how this works behind the scenes for performance reasons. I am not familiar enaugh with IL to look into this.

推荐答案

这是一个新的字符串。

字符串,在.NET中,总是一成不变。当你通过一个方法,包括子串生成一个新的字符串,它会建立在内存中的新的字符串。您共享同一数据引用的字符串.NET中唯一的一次是,如果你明确指定一个字符串变量到另一个字符串(在其复制参考),或者如果你用字符串常量,这是典型实习工作。如果你知道你的字符串要分享与实习字符串值(恒定/从你的代码中的文字),可以检索共享通过的中的String.intern

Strings, in .NET, are always immutable. Whenever you generate a new string via a method, including Substring, it will construct the new string in memory. The only time you share references to the same data in strings in .NET is if you explicitly assign a string variable to another string (in which its copying the reference), or if you work with string constants, which are typically interned. If you know your string is going to share a value with an interned string (constant/literal from your code), you can retrieve the "shared" copy via String.Intern.

这是一件好事,顺便说一句 - 在为了做到你被描述什么,每串将需要一个参考(字符串数据),以及作为偏移+长度。现在,他们只需要对字符串数据的参考。

This is a good thing, btw - In order to do what you were describing, every string would require a reference (to the string data), as well as an offset + length. Right now, they only require a reference to the string data.

这将大大增加一般串的大小,在整个框架

This would dramatically increase the size of strings in general, throughout the framework.

这篇关于当净获得子,并在新的字符串引用相同的原始字符串数据还是数据被复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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