C# - array index vs LINQ?
What, if any, would be the performance difference between these?
/// option 1
string result = data.Split('.').Last<string>();
/// option 2
string[] parts = data.Split('.');
string result = data[data.Length-1];
/// option 3
string result = data.Substring(data.LastIndexOf('.')+1);
Assume that data
is a string in the format of part1.part2.part3
.
Edit
开发者_高级运维This is really more idle curiosity than anything else. I haven't cracked open reflector to see what's happening inside of LINQ, but I don't see how it could be faster than direct array manipulation. Thanks for the tips.
void Main()
{
var tester = new testing();
var runTimeOne = tester.optionOne();
runTimeOne.Dump();
var runTimeTwo = tester.optionTwo();
runTimeTwo.Dump();
var runTimeThree = tester.optionThree();
runTimeThree.Dump();
}
public class testing
{
public String dataString = "part1.part2.part3";
public int numRuns = 1000000;
public TimeSpan optionOne()
{
var startTime = DateTime.Now;
for(var i = 0; i < numRuns; i++)
{
string result = dataString.Split('.').Last<string>();
}
return (DateTime.Now - startTime);
}
public TimeSpan optionTwo()
{
var startTime = DateTime.Now;
for(var i = 0; i < numRuns; i++)
{
string[] parts = dataString.Split('.');
string result = parts[parts.Length-1];
}
return (DateTime.Now - startTime);
}
public TimeSpan optionThree()
{
var startTime = DateTime.Now;
for(var i = 0; i < numRuns; i++)
{
string result = dataString.Substring(dataString.LastIndexOf('.')+1);
}
return (DateTime.Now - startTime);
}
}
Result:
00:00:00.9660552
00:00:00.2010115
00:00:00.0360021
If you really care, measure it.
I would guess option 3) to be a little faster than the other 2.
But that's only a guess.
Options 1 and 2 are identical in terms of performance because the Last extension method checks whether the underlying enmerable has an indexer and if it does it simply returns the last element. As far as option 3 is concerned you will need to measure it with the other two but I suspect there will be a negligible difference.
For small strings the difference would be small, but for large strings the third option is clearly more efficient.
The first two options will scan the entire string and copy it into new strings and create an array of the strings. The third option will just scan the string from the end to look for the period, and just create the one string that is needed.
So, for a specific use you would measure which method is most efficient for the specific data that you have, but for general use the third option is the best because it scales much better.
精彩评论