Emerion
Emerion

Reputation: 810

Methods: What is better List or object?

While I was programming I came up with this question,

What is better, having a method accept a single entity or a List of those entity's?

For example I need a List of strings. I can either have:

or

** This is just a example. I need to know which one is better, or more used and why.

Thanks!

Upvotes: 1

Views: 447

Answers (3)

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29640

I would choose the second because it's easier to use when you have a single string (i.e. it's more general purpose). Also, the responsibility of the method itself is more clear because the method should not have anything to do with lists if it's purpose is just to modify a string.

Also, you can simplify the call with Linq:

result = yourList.Select(p => methodwithsingleobject(p));

Upvotes: 2

Liam
Liam

Reputation: 1768

This question comes up a lot when learning any language, the answer is somewhat moot since the standard coding practice is to rely upon LINQ to optimize the code for you at runtime. But this presumes you're using a version of the language that supports it. But if you do want to do some research on this there are a few Stack Overflow articles that delve into this and also give external resources to review:

  1. In .NET, which loop runs faster, 'for' or 'foreach'?
  2. C#, For Loops, and speed test... Exact same loop faster second time around?

What I have learned, though, is not to rely too heavily on Count and to use Length on typed Collections as that can be a lot faster.

Hope this is helpful.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503479

Well, it's easy to build the first form when you've got the second - but using LINQ, you really don't need to write your own, once you've got the projection. For example, you could write:

List<string> results = objectList.Select(X => MethodWithSingleObject()).ToList();

Generally it's easier to write and test a method which only deals with a single value, unless it actually needs to know the rest of the values in the collection (e.g. to find aggregates).

Upvotes: 7

Related Questions