Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid creating a new list on SmartEnum.List #521

Closed
fiseni opened this issue Apr 27, 2024 · 3 comments · Fixed by #497
Closed

Avoid creating a new list on SmartEnum.List #521

fiseni opened this issue Apr 27, 2024 · 3 comments · Fixed by #497

Comments

@fiseni
Copy link

fiseni commented Apr 27, 2024

The SmartEnum.List currently is implemented as follows.

public static IReadOnlyCollection<TEnum> List =>
    _fromName.Value.Values
        .ToList()
        .AsReadOnly();

This API might be frequently called by the consumers, and creating a new list doesn't make much sense. Moreover, this is a property, and the consumer expects that the properties return precalculated fields. They shouldn't contain heavy operations or create additional allocations. If that's the case, then usually the API should be defined as a method, e.g. GetList().

We already keep the collection of discovered enums as Lazy<TEnum[]>. But, even internally this collection is never altered, so I suggest the state be kept as ReadOnlyCollection instead of an array, and List simply would return this field.

static readonly Lazy<ReadOnlyCollection<TEnum>> _enumOptions = 
    new Lazy<ReadOnlyCollection<TEnum>>(GetAllOptions, LazyThreadSafetyMode.ExecutionAndPublication);
	
public static IReadOnlyList<TEnum> List => _enumOptions.Value;

Note: The ReadOnlyCollection is proposed since not all targetted TFMs support newer collection types.

@ardalis
Copy link
Owner

ardalis commented Apr 27, 2024

Sounds good, thanks!

@ardalis
Copy link
Owner

ardalis commented Apr 27, 2024

hey @akarboush is this something you'd want to knock out?

@akarboush
Copy link
Contributor

@ardalis sure, PR is updated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants