String.Intern(String) 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
지정된 String에 대한 시스템의 참조를 검색합니다.
public:
static System::String ^ Intern(System::String ^ str);
public static string Intern(string str);
static member Intern : string -> string
Public Shared Function Intern (str As String) As String
매개 변수
- str
- String
인턴 풀에서 검색할 문자열입니다.
반품
인턴되는 경우 시스템에 대한 참조 str이고, 그렇지 않으면 값 str이 있는 문자열에 대한 새 참조입니다.
예외
str은 null입니다.
예제
다음 예제에서는 값이 같은 두 문자열을 만들고 인턴링하면 동일한 참조가 생성된다는 것을 보여 줍니다.
// Sample for String.Intern(String)
using System;
using System.Text;
class Sample
{
public static void Main()
{
string s1 = new StringBuilder().Append("My").Append("Test").ToString();
string s2 = new StringBuilder().Append("My").Append("Test").ToString();
Console.WriteLine($"s1 == {s1}");
Console.WriteLine($"s2 == {s2}");
Console.WriteLine($"Are s1 and s2 equal in value? {s1 == s2}");
Console.WriteLine($"Are s1 and s2 the same reference? {Object.ReferenceEquals(s1, s2)}");
string i1 = String.Intern(s1);
string i2 = String.Intern(s2);
Console.WriteLine($"After interning:");
Console.WriteLine($" Are i1 and i2 equal in value? {i1 == i2}");
Console.WriteLine($" Are i1 and i2 the same reference? {Object.ReferenceEquals(i1, i2)}");
}
}
/*
This example produces the following results:
s1 == MyTest
s2 == MyTest
Are s1 and s2 equal in value? True
Are s1 and s2 the same reference? False
After interning:
Are i1 and i2 equal in value? True
Are i1 and i2 the same reference? True
*/
// Sample for String.Intern(String)
open System
open System.Text
let s1 = StringBuilder().Append("My").Append("Test").ToString()
let s2 = StringBuilder().Append("My").Append("Test").ToString()
printfn $"s1 = {s1}"
printfn $"s2 = {s2}"
printfn $"Are s1 and s2 equal in value? {s1 = s2}"
printfn $"Are s1 and s2 the same reference? {Object.ReferenceEquals(s1, s2)}"
let i1 = String.Intern s1
let i2 = String.Intern s2
printfn "After interning:"
printfn $" Are i1 and i2 equal in value? {i1 = i2}"
printfn $" Are i1 and i2 the same reference? {Object.ReferenceEquals(i1, i2)}"
(*
This example produces the following results:
s1 = MyTest
s2 = MyTest
Are s1 and s2 equal in value? True
Are s1 and s2 the same reference? False
After interning:
Are i1 and i2 equal in value? True
Are i1 and i2 the same reference? True
*)
Imports System.Text
Class Sample
Public Shared Sub Run()
Dim s1 As String = New StringBuilder().Append("My").Append("Test").ToString()
Dim s2 As String = New StringBuilder().Append("My").Append("Test").ToString()
Console.WriteLine($"s1 = {s1}")
Console.WriteLine($"s2 = {s2}")
Console.WriteLine($"Are s1 and s2 equal in value? {s1 = s2}")
Console.WriteLine($"Are s1 and s2 the same reference? {s1 Is s2}")
Dim i1 As String = String.Intern(s1)
Dim i2 As String = String.Intern(s2)
Console.WriteLine("After interning:")
Console.WriteLine($" Are i1 and i2 equal in value? {i1 = i2}")
Console.WriteLine($" Are i1 and i2 the same reference? {i1 Is i2}")
End Sub
End Class
'
's1 = MyTest
's2 = MyTest
'Are s1 and s2 equal in value? True
'Are s1 and s2 the same reference? False
'After interning:
' Are i1 and i2 equal in value? True
' Are i1 and i2 the same reference? True
'
설명
! [참고] >
String.Intern값이 같은 두 문자열이 동일한 인턴 참조를 반환한다고 보장하지만 반환된 참조가 문자열 리터럴과 동일하다는 보장은 없습니다.
The common language runtime maintains a table, called the *intern pool*, that holds a single reference for each unique string value. The <xref:System.String.Intern*> method uses the intern pool to search for a string equal to the value of `str`. If no such string exists, a reference to `str` is added to the pool, and that reference is returned. (In contrast, the <xref:System.String.IsInterned(System.String)> method returns a null reference if the requested string doesn't exist in the intern pool.)
인턴 풀은 런타임에서 문자열 스토리지를 절약하는 데 사용할 수 있습니다. 그러나 문자열 리터럴의 자동 인턴팅은 보장되지 않습니다. 어셈블리가 컴파일되고 실행되는 방법에 따라 일부 리터럴이 풀에 추가되지 않을 수 있습니다.
다음 예제에서 문자열 s1 의 값은 "MyTest"입니다. 클래스는 System.Text.StringBuilder 값이 같은 s1새 문자열 개체를 생성합니다. 해당 문자열에 대한 참조가 .에 s2할당됩니다. 메서드는 Intern 값 s2이 같은 문자열을 검색합니다. 이미 인턴된 경우(예: 어셈블리에 문자열 리터럴 인턴링이 필요하기 때문에) 메서드는 s1과 동일한 참조를 반환하며, 이 참조는 s1에 할당됩니다. 그리고 s3와 s1는 같음으로 비교됩니다. 그렇지 않으면 s2에 대한 새로운 인턴된 항목이 만들어지고 s3에 할당되며, s1와 s3는 같지 않음을 비교합니다.
s1와 s2는 두 경우 모두 서로 다른 개체를 참조하므로 같지 않다고 비교합니다.
string s1 = "MyTest";
string s2 = new StringBuilder().Append("My").Append("Test").ToString();
string s3 = String.Intern(s2);
Console.WriteLine((Object)s2==(Object)s1); // Different references.
Console.WriteLine((Object)s3==(Object)s1); // The same reference.
let s1 = "MyTest"
let s2 = StringBuilder().Append("My").Append("Test").ToString()
let s3 = String.Intern s2
printfn $"{s2 :> obj = s1 :> obj}" // Different references.
printfn $"{s3 :> obj = s1 :> obj}" // The same reference.
Dim s1 As String = "MyTest"
Dim s2 As String = New StringBuilder().Append("My").Append("Test").ToString()
Dim s3 As String = String.Intern(s2)
Console.WriteLine(CObj(s2) Is CObj(s1)) ' Different references.
Console.WriteLine(CObj(s3) Is CObj(s1)) ' The same reference.
성능 고려 사항
애플리케이션에서 할당하는 총 메모리 양을 줄이려는 경우 문자열 인턴팅에는 두 가지 원치 않는 부작용이 있음을 명심하세요. 첫째, 인턴 String 된 개체에 할당된 메모리는 CLR(공용 언어 런타임)이 종료될 때까지 해제될 가능성이 없습니다. 그 이유는 애플리케이션 또는 애플리케이션 도메인이 종료된 후에도 CLR이 인턴 String 된 개체에 대한 참조를 유지할 수 있기 때문입니다. 둘째, 문자열을 인터닝하려면 먼저 문자열을 만들어야 합니다. String 개체에서 사용하는 메모리는 결국 가비지 수집될 것이지만, 여전히 할당되어야 합니다.
열거형 멤버는 CompilationRelaxations.NoStringInterning 문자열 리터럴 인턴링을 요구하지 않는 어셈블리를 표시합니다. 기본적으로 C# 컴파일러는 성능 향상을 위해 각 어셈블리마다 CompilationRelaxationsAttribute를 NoStringInterning 플래그와 함께 생성합니다. 이는 문자열 리터럴이 인턴 풀에 추가될 것을 보장하지 않음을 의미합니다. NoStringInterning에 CompilationRelaxationsAttribute 특성을 사용하여 어셈블리를 사용자 지정할 수 있습니다.
네이티브 AOT를 사용하여 앱을 게시하는 경우 해제 NoStringInterning 는 지원되지 않습니다. 네이티브 AOT에서는 문자열 리터럴이 인턴 풀에 추가되도록 보장되지 않으므로 Intern 소스 코드에서 리터럴로 보이는 문자열에 대한 일치 항목을 찾을 수 없습니다.