Skip to content

Efficient way to pass in immutable/non-array collections #55

@charlesroddie

Description

@charlesroddie

CBORObject.FromObject has an overload taking arrays:

    public static CBORObject FromObject(CBORObject[] array) {
      if (array == null) {
        return CBORObject.Null;
      }
      IList<CBORObject> list = new List<CBORObject>();
      foreach (CBORObject cbor in array) {
        list.Add(cbor);
      }
      return new CBORObject(CBORObjectTypeArray, list);
    }

There is an additional collection created here: since array is mutable it cannot be trusted to be used directly, so it is duplicated into an List.

Passing in collections other than arrays take a further collection creation, as they first need to be converted to arrays since that is the only overload.

It would be good to have an efficient way to pass in an ImmutableArray<CBORObject>, or one of the interfaces that it supports: ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, IImmutableList<T>.

This could be done by taking an IEnumerable<T> and using the current approach. That would only be one collection creation, copying to a List.

If it used one of the immutable interfaces internally (ImmutableArray, IImmutableList), then no copying would be needed, as the input could be used directly without risk of changes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions