String.Format StringBuilder
आंतरिक रूप से उपयोग करता है ... इसलिए तार्किक रूप से इस विचार की ओर जाता है कि यह अधिक उपरि के कारण थोड़ा कम प्रदर्शन करने वाला होगा। हालांकि, एक साधारण स्ट्रिंग का संघनन एक स्ट्रिंग को दो अन्य के बीच इंजेक्ट करने का सबसे तेज़ तरीका है ... एक महत्वपूर्ण डिग्री द्वारा। इस साक्ष्य का प्रदर्शन रिको मारियानी ने अपने पहले प्रदर्शन क्विज़ में वर्षों पहले किया था। सरल तथ्य यह है कि संघनन ... जब स्ट्रिंग भागों की संख्या ज्ञात होती है (बिना किसी सीमा के..आप एक हजार भागों को मिला सकते हैं ... जब तक आप इसके 1000 भागों को जानते हैं) ... हमेशा की तुलना में StringBuilder
या स्ट्रिंग से अधिक तेज़ होते हैं । स्वरूप। उन्हें एकल मेमोरी आवंटन के साथ स्मृति प्रतियों की एक श्रृंखला के साथ किया जा सकता है। यहाँ सबूत है
और यहाँ कुछ String.Concat तरीकों के लिए वास्तविक कोड है, जो अंततः FillStringChecked कहते हैं जो मेमोरी की प्रतिलिपि बनाने के लिए पॉइंटर्स का उपयोग करता है (रिफ्लेक्टर के माध्यम से निकाला जाता है):
public static string Concat(params string[] values)
{
int totalLength = 0;
if (values == null)
{
throw new ArgumentNullException("values");
}
string[] strArray = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
string str = values[i];
strArray[i] = (str == null) ? Empty : str;
totalLength += strArray[i].Length;
if (totalLength < 0)
{
throw new OutOfMemoryException();
}
}
return ConcatArray(strArray, totalLength);
}
public static string Concat(string str0, string str1, string str2, string str3)
{
if (((str0 == null) && (str1 == null)) && ((str2 == null) && (str3 == null)))
{
return Empty;
}
if (str0 == null)
{
str0 = Empty;
}
if (str1 == null)
{
str1 = Empty;
}
if (str2 == null)
{
str2 = Empty;
}
if (str3 == null)
{
str3 = Empty;
}
int length = ((str0.Length + str1.Length) + str2.Length) + str3.Length;
string dest = FastAllocateString(length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, str0.Length, str1);
FillStringChecked(dest, str0.Length + str1.Length, str2);
FillStringChecked(dest, (str0.Length + str1.Length) + str2.Length, str3);
return dest;
}
private static string ConcatArray(string[] values, int totalLength)
{
string dest = FastAllocateString(totalLength);
int destPos = 0;
for (int i = 0; i < values.Length; i++)
{
FillStringChecked(dest, destPos, values[i]);
destPos += values[i].Length;
}
return dest;
}
private static unsafe void FillStringChecked(string dest, int destPos, string src)
{
int length = src.Length;
if (length > (dest.Length - destPos))
{
throw new IndexOutOfRangeException();
}
fixed (char* chRef = &dest.m_firstChar)
{
fixed (char* chRef2 = &src.m_firstChar)
{
wstrcpy(chRef + destPos, chRef2, length);
}
}
}
तो फिर:
string what = "cat";
string inthehat = "The " + what + " in the hat!";
का आनंद लें!