1

I'm implementing a library that parses JSON data into various C# objects using Newtonsoft's LINQ to JSON functions. Apart from the lazy vs. eager approach, is there any impact to passing some other library's IEnumerable vs. dumping it into a List and then returning that? Does this allow better garbage collection or anything along those lines?

public class SimpleClass
{
    public IEnumerable<string> Tags { get; private set; }

    // Assume the token passed is a valid array of strings.
    public void UpdateTags1(JToken token)
    {
        this.Tags = token["tags"].Values<string>();
    }

    public void UpdateTags2(JToken token)
    {
        this.Tags = new List<string>(token["tags"].Values<string>());
    }
}
  • 1
    I don't think so. All assemblies are loaded into memory at this point and basically there is no difference between your library dll and json.net library dll. Especially if you work inside the same app domain and don't perform marshaling. – abatishchev Feb 14 '15 at 06:21
  • By the way, accessing Tag assigned by UpdateTags1() may cause multiple IEnumerable enumeration down to JToken.Values(). So I'd have `ICollection` instead and force materialization using `ToArray()`. – abatishchev Feb 14 '15 at 06:24
  • Yeah, I'm aware of that issue. This is a low-level library, though. The assumption is that any developer consuming it will themselves convert the IEnumerable to a List or whatever else they want. (At least that's the theory...what a developer does in reality is another matter.) –  Feb 14 '15 at 06:32

1 Answers1

1

There is no difference at all with respect to whether the Values<string>() method is in the same assembly or a different one.

However, it's worth noting that there is a practical difference, depending on what the Values<string>() method is actually returning. Often when an instance of IEnumerable<T> is returned, the sequence is a result of deferred execution. I.e. until you evaluate the sequence, it doesn't actually exist.

More to the point, it is recreated every time you evaluate it. Depending on the evaluation, this may or may not be a problem. At the very least, it could be a performance issue. It is also possible that the result of the evaluation could change between evaluations.

When you aren't positively sure this would not be a problem, it is often a good idea to convert to a list or array, just to make sure you get a fully-evaluated sequence. You can do this as in your example, or by calling e.g. the ToList() or ToArray() extension methods on the result.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136