क्यों यह संभव string
पर धाराप्रवाह भाषा का उपयोग नहीं है?स्ट्रिंग करने के लिए IENumerable <char> को परिवर्तित करने का सबसे अच्छा तरीका?
उदाहरण के लिए:
var x = "asdf1234";
var y = new string(x.TakeWhile(char.IsLetter).ToArray());
वहाँ एक बेहतर तरीका string
को IEnumerable<char>
कन्वर्ट करने के लिए नहीं है?
यहाँ एक परीक्षण मैं लगा रहे:
class Program
{
static string input = "asdf1234";
static void Main()
{
Console.WriteLine("1000 times:");
RunTest(1000, input);
Console.WriteLine("10000 times:");
RunTest(10000,input);
Console.WriteLine("100000 times:");
RunTest(100000, input);
Console.WriteLine("100000 times:");
RunTest(100000, "ffff57467");
Console.ReadKey();
}
static void RunTest(int times, string input)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < times; i++)
{
string output = new string(input.TakeWhile(char.IsLetter).ToArray());
}
sw.Stop();
var first = sw.ElapsedTicks;
sw.Restart();
for (int i = 0; i < times; i++)
{
string output = Regex.Match(input, @"^[A-Z]+",
RegexOptions.IgnoreCase).Value;
}
sw.Stop();
var second = sw.ElapsedTicks;
var regex = new Regex(@"^[A-Z]+",
RegexOptions.IgnoreCase);
sw.Restart();
for (int i = 0; i < times; i++)
{
var output = regex.Match(input).Value;
}
sw.Stop();
var third = sw.ElapsedTicks;
double percent = (first + second + third)/100;
double p1 = (first/percent)/ 100;
double p2 = (second/percent)/100;
double p3 = (third/percent )/100;
Console.WriteLine("TakeWhile took {0} ({1:P2}).,", first, p1);
Console.WriteLine("Regex took {0}, ({1:P2})." , second,p2);
Console.WriteLine("Preinstantiated Regex took {0}, ({1:P2}).", third,p3);
Console.WriteLine();
}
}
परिणाम:
1000 times:
TakeWhile took 11217 (62.32%).,
Regex took 5044, (28.02%).
Preinstantiated Regex took 1741, (9.67%).
10000 times:
TakeWhile took 9210 (14.78%).,
Regex took 32461, (52.10%).
Preinstantiated Regex took 20669, (33.18%).
100000 times:
TakeWhile took 74945 (13.10%).,
Regex took 324520, (56.70%).
Preinstantiated Regex took 172913, (30.21%).
100000 times:
TakeWhile took 74511 (13.77%).,
Regex took 297760, (55.03%).
Preinstantiated Regex took 168911, (31.22%).
निष्कर्ष: मैं पर शक कर रहा हूँ क्या पसंद करते हैं करने के लिए बेहतर है, मुझे लगता है कि मैं TakeWhile
पर जाना चाहता हूँ जो केवल पहले रन पर सबसे धीमा है।
वैसे भी, मेरा सवाल यह है कि TakeWhile
फ़ंक्शन के परिणाम को पुन: प्रयास करके प्रदर्शन को अनुकूलित करने का कोई तरीका है।
कृपया बताएं कि आपका क्या मतलब है "सर्वश्रेष्ठ": सबसे तेज़? कम स्मृति-भूखे? समझने के लिए सबसे आसान है? – LukeH
@LukeH मैंने पहले से ही अपना निर्णय लिया है कि क्या चुनना है: उपवास। अगर वहाँ 'नई स्ट्रिंग (x.TakeWhile (पी) .ToArray) की तुलना में एक अच्छे तरीका है मेरा प्रश्न है' – Shimmy
@LukeH: अपने समाधान हटाना चाहते हैं सकता है: यह एक बहुत बड़े अंतर – BrokenGlass