Which is faster in execution or is more optimized? C#
I'm not sure if it's ok to ask this kind of question here, but I just want to know the difference between the two code snippets.
As I was browsing the questions here in SO, I found this post: How to find the number of HTML elements with a name that starts with a certain string in c#?
a user answered this:
var dictionary = Request.Form.Keys
.Cast<string>()
.Where(x => x.StartsWith("abc"))
.ToDictionary(x => x, x => Request.Form[x]);
Retur开发者_如何学Pythonns a dictionary containing the keys/values for all form elements that start with "abc".
Update: The poor OP is using .Net 2.0. So here is the old-school answer:
Dictionary<string, string> keys = new Dictionary<string, string>();
foreach (string key in request.Form.Keys)
{
if (key.StartsWith("abc"))
keys[key] = request.Form[key];
}
Which of the two is faster in execution or is more optimized? Should we never use the old one?
This is an excellent example of 'over optimization'. The code isn't executing inside an inner loop and if you profile it you'll see it's much less than 0.1% of the execution time of your application.
So in this case ease of readability, reliability, and maintainability are much larger concerns. Given that both snippets do the job reliably, which one would you want to read 9 months from now when you've forgotten how this code works?
The performance difference will be negligible and not worth worrying about. It may also vary from one version of .NET to the next.
The reason that the first approach is preferable is that you are declaring WHAT you want rather than HOW to calculate it. Once you get used to that style of programming you'll likely prefer it.
Declaring it this way makes it easier to parallelize later (and potentially easier for the compiler to optimize).
See http://www.albahari.com/threading/part5.aspx for more discussion on declarative programming and how it makes parallelization easier.
[Of course in THIS case where the calculation is so simple you'll never want to parallelize it but in general, when the loop contains more complex code, you might.]
In terms of Big O, it's equivalent. It's an efficient one-pass algorithm either way. There might be some slight overhead in the LINQ version, but it's pretty much the same, and you should choose based on readability.
Same thing, just newfangled. But it will execute effectively the same way.
精彩评论