More efficient array creation (#11468)

This commit is contained in:
Bond-009 2024-04-30 21:32:59 +02:00 committed by GitHub
parent 5dc6bb4910
commit 3feb3f81bf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
25 changed files with 55 additions and 131 deletions

View File

@ -127,15 +127,11 @@ namespace Emby.Server.Implementations.AppBase
if (_configurationFactories is null) if (_configurationFactories is null)
{ {
_configurationFactories = new[] { factory }; _configurationFactories = [factory];
} }
else else
{ {
var oldLen = _configurationFactories.Length; _configurationFactories = [.._configurationFactories, factory];
var arr = new IConfigurationFactory[oldLen + 1];
_configurationFactories.CopyTo(arr, 0);
arr[oldLen] = factory;
_configurationFactories = arr;
} }
_configurationStores = _configurationFactories _configurationStores = _configurationFactories

View File

@ -2323,14 +2323,7 @@ namespace Emby.Server.Implementations.Data
columns.Add(builder.ToString()); columns.Add(builder.ToString());
var oldLen = query.ExcludeItemIds.Length; query.ExcludeItemIds = [..query.ExcludeItemIds, item.Id, ..item.ExtraIds];
var newLen = oldLen + item.ExtraIds.Length + 1;
var excludeIds = new Guid[newLen];
query.ExcludeItemIds.CopyTo(excludeIds, 0);
excludeIds[oldLen] = item.Id;
item.ExtraIds.CopyTo(excludeIds, oldLen + 1);
query.ExcludeItemIds = excludeIds;
query.ExcludeProviderIds = item.ProviderIds; query.ExcludeProviderIds = item.ProviderIds;
} }
@ -2838,10 +2831,7 @@ namespace Emby.Server.Implementations.Data
prepend.Add((ItemSortBy.Random, SortOrder.Ascending)); prepend.Add((ItemSortBy.Random, SortOrder.Ascending));
} }
var arr = new (ItemSortBy, SortOrder)[prepend.Count + orderBy.Count]; orderBy = query.OrderBy = [..prepend, ..orderBy];
prepend.CopyTo(arr, 0);
orderBy.CopyTo(arr, prepend.Count);
orderBy = query.OrderBy = arr;
} }
else if (orderBy.Count == 0) else if (orderBy.Count == 0)
{ {

View File

@ -103,7 +103,7 @@ namespace Emby.Server.Implementations.Library
} }
}; };
private static readonly Glob[] _globs = _patterns.Select(p => Glob.Parse(p, _globOptions)).ToArray(); private static readonly Glob[] _globs = Array.ConvertAll(_patterns, p => Glob.Parse(p, _globOptions));
/// <summary> /// <summary>
/// Returns true if the supplied path should be ignored. /// Returns true if the supplied path should be ignored.

View File

@ -3038,9 +3038,7 @@ namespace Emby.Server.Implementations.Library
{ {
var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath); var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
var list = libraryOptions.PathInfos.ToList(); libraryOptions.PathInfos = [..libraryOptions.PathInfos, pathInfo];
list.Add(pathInfo);
libraryOptions.PathInfos = list.ToArray();
SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions); SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
@ -3059,8 +3057,7 @@ namespace Emby.Server.Implementations.Library
SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions); SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
var list = libraryOptions.PathInfos.ToList(); foreach (var originalPathInfo in libraryOptions.PathInfos)
foreach (var originalPathInfo in list)
{ {
if (string.Equals(mediaPath.Path, originalPathInfo.Path, StringComparison.Ordinal)) if (string.Equals(mediaPath.Path, originalPathInfo.Path, StringComparison.Ordinal))
{ {
@ -3069,8 +3066,6 @@ namespace Emby.Server.Implementations.Library
} }
} }
libraryOptions.PathInfos = list.ToArray();
CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions); CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
} }

View File

@ -303,8 +303,8 @@ namespace Emby.Server.Implementations.Library
{ {
// Handle situations with the grouping setting, e.g. movies showing up in tv, etc. // Handle situations with the grouping setting, e.g. movies showing up in tv, etc.
// Thanks to mixed content libraries included in the UserView // Thanks to mixed content libraries included in the UserView
var hasCollectionType = parents.OfType<UserView>().ToArray(); var hasCollectionType = parents.OfType<UserView>().ToList();
if (hasCollectionType.Length > 0) if (hasCollectionType.Count > 0)
{ {
if (hasCollectionType.All(i => i.CollectionType == CollectionType.movies)) if (hasCollectionType.All(i => i.CollectionType == CollectionType.movies))
{ {

View File

@ -226,13 +226,8 @@ namespace Emby.Server.Implementations.Playlists
return; return;
} }
// Create a new array with the updated playlist items
var newLinkedChildren = new LinkedChild[playlist.LinkedChildren.Length + childrenToAdd.Count];
playlist.LinkedChildren.CopyTo(newLinkedChildren, 0);
childrenToAdd.CopyTo(newLinkedChildren, playlist.LinkedChildren.Length);
// Update the playlist in the repository // Update the playlist in the repository
playlist.LinkedChildren = newLinkedChildren; playlist.LinkedChildren = [..playlist.LinkedChildren, ..childrenToAdd];
await UpdatePlaylistInternal(playlist).ConfigureAwait(false); await UpdatePlaylistInternal(playlist).ConfigureAwait(false);
@ -526,8 +521,8 @@ namespace Emby.Server.Implementations.Playlists
foreach (var playlist in playlists) foreach (var playlist in playlists)
{ {
// Update owner if shared // Update owner if shared
var rankedShares = playlist.Shares.OrderByDescending(x => x.CanEdit).ToArray(); var rankedShares = playlist.Shares.OrderByDescending(x => x.CanEdit).ToList();
if (rankedShares.Length > 0) if (rankedShares.Count > 0)
{ {
playlist.OwnerUserId = rankedShares[0].UserId; playlist.OwnerUserId = rankedShares[0].UserId;
playlist.Shares = rankedShares.Skip(1).ToArray(); playlist.Shares = rankedShares.Skip(1).ToArray();

View File

@ -256,8 +256,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{ {
get get
{ {
var triggers = InternalTriggers; return Array.ConvertAll(InternalTriggers, i => i.Item1);
return triggers.Select(i => i.Item1).ToArray();
} }
set set
@ -269,7 +268,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
SaveTriggers(triggerList); SaveTriggers(triggerList);
InternalTriggers = triggerList.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray(); InternalTriggers = Array.ConvertAll(triggerList, i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i)));
} }
} }
@ -503,7 +502,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers() private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
{ {
// This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
var settings = LoadTriggerSettings().Where(i => i is not null).ToArray(); var settings = LoadTriggerSettings().Where(i => i is not null);
return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray(); return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
} }

View File

@ -400,7 +400,7 @@ namespace Emby.Server.Implementations.Session
{ {
session.NowPlayingQueue = nowPlayingQueue; session.NowPlayingQueue = nowPlayingQueue;
var itemIds = nowPlayingQueue.Select(queue => queue.Id).ToArray(); var itemIds = Array.ConvertAll(nowPlayingQueue, queue => queue.Id);
session.NowPlayingQueueFullItems = _dtoService.GetBaseItemDtos( session.NowPlayingQueueFullItems = _dtoService.GetBaseItemDtos(
_libraryManager.GetItemList(new InternalItemsQuery { ItemIds = itemIds }), _libraryManager.GetItemList(new InternalItemsQuery { ItemIds = itemIds }),
new DtoOptions(true)); new DtoOptions(true));
@ -1386,16 +1386,13 @@ namespace Emby.Server.Implementations.Session
if (session.AdditionalUsers.All(i => !i.UserId.Equals(userId))) if (session.AdditionalUsers.All(i => !i.UserId.Equals(userId)))
{ {
var user = _userManager.GetUserById(userId); var user = _userManager.GetUserById(userId);
var newUser = new SessionUserInfo
var list = session.AdditionalUsers.ToList();
list.Add(new SessionUserInfo
{ {
UserId = userId, UserId = userId,
UserName = user.Username UserName = user.Username
}); };
session.AdditionalUsers = list.ToArray(); session.AdditionalUsers = [..session.AdditionalUsers, newUser];
} }
} }

View File

@ -264,7 +264,7 @@ public class ItemUpdateController : BaseJellyfinApiController
if (request.Studios is not null) if (request.Studios is not null)
{ {
item.Studios = request.Studios.Select(x => x.Name).ToArray(); item.Studios = Array.ConvertAll(request.Studios, x => x.Name);
} }
if (request.DateCreated.HasValue) if (request.DateCreated.HasValue)
@ -379,10 +379,7 @@ public class ItemUpdateController : BaseJellyfinApiController
{ {
if (item is IHasAlbumArtist hasAlbumArtists) if (item is IHasAlbumArtist hasAlbumArtists)
{ {
hasAlbumArtists.AlbumArtists = request hasAlbumArtists.AlbumArtists = Array.ConvertAll(request.AlbumArtists, i => i.Name);
.AlbumArtists
.Select(i => i.Name)
.ToArray();
} }
} }
@ -390,10 +387,7 @@ public class ItemUpdateController : BaseJellyfinApiController
{ {
if (item is IHasArtist hasArtists) if (item is IHasArtist hasArtists)
{ {
hasArtists.Artists = request hasArtists.Artists = Array.ConvertAll(request.ArtistItems, i => i.Name);
.ArtistItems
.Select(i => i.Name)
.ToArray();
} }
} }

View File

@ -158,13 +158,13 @@ public class LibraryController : BaseJellyfinApiController
return NotFound(); return NotFound();
} }
IEnumerable<BaseItem> themeItems; IReadOnlyList<BaseItem> themeItems;
while (true) while (true)
{ {
themeItems = item.GetThemeSongs(); themeItems = item.GetThemeSongs();
if (themeItems.Any() || !inheritFromParent) if (themeItems.Count > 0 || !inheritFromParent)
{ {
break; break;
} }

View File

@ -85,7 +85,7 @@ public class LibraryStructureController : BaseJellyfinApiController
if (paths is not null && paths.Length > 0) if (paths is not null && paths.Length > 0)
{ {
libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo(i)).ToArray(); libraryOptions.PathInfos = Array.ConvertAll(paths, i => new MediaPathInfo(i));
} }
await _libraryManager.AddVirtualFolder(name, collectionType, libraryOptions, refreshLibrary).ConfigureAwait(false); await _libraryManager.AddVirtualFolder(name, collectionType, libraryOptions, refreshLibrary).ConfigureAwait(false);

View File

@ -85,16 +85,11 @@ public class UserViewsController : BaseJellyfinApiController
var folders = _userViewManager.GetUserViews(query); var folders = _userViewManager.GetUserViews(query);
var dtoOptions = new DtoOptions().AddClientFields(User); var dtoOptions = new DtoOptions().AddClientFields(User);
var fields = dtoOptions.Fields.ToList(); dtoOptions.Fields = [..dtoOptions.Fields, ItemFields.PrimaryImageAspectRatio, ItemFields.DisplayPreferencesId];
fields.Add(ItemFields.PrimaryImageAspectRatio);
fields.Add(ItemFields.DisplayPreferencesId);
dtoOptions.Fields = fields.ToArray();
var user = _userManager.GetUserById(userId.Value); var user = _userManager.GetUserById(userId.Value);
var dtos = folders.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user)) var dtos = Array.ConvertAll(folders, i => _dtoService.GetBaseItemDto(i, dtoOptions, user));
.ToArray();
return new QueryResult<BaseItemDto>(dtos); return new QueryResult<BaseItemDto>(dtos);
} }

View File

@ -43,11 +43,7 @@ public static class DtoExtensions
client.Contains("media center", StringComparison.OrdinalIgnoreCase) || client.Contains("media center", StringComparison.OrdinalIgnoreCase) ||
client.Contains("classic", StringComparison.OrdinalIgnoreCase)) client.Contains("classic", StringComparison.OrdinalIgnoreCase))
{ {
int oldLen = dtoOptions.Fields.Count; dtoOptions.Fields = [..dtoOptions.Fields, ItemFields.RecursiveItemCount];
var arr = new ItemFields[oldLen + 1];
dtoOptions.Fields.CopyTo(arr, 0);
arr[oldLen] = ItemFields.RecursiveItemCount;
dtoOptions.Fields = arr;
} }
} }
@ -61,11 +57,7 @@ public static class DtoExtensions
client.Contains("samsung", StringComparison.OrdinalIgnoreCase) || client.Contains("samsung", StringComparison.OrdinalIgnoreCase) ||
client.Contains("androidtv", StringComparison.OrdinalIgnoreCase)) client.Contains("androidtv", StringComparison.OrdinalIgnoreCase))
{ {
int oldLen = dtoOptions.Fields.Count; dtoOptions.Fields = [..dtoOptions.Fields, ItemFields.ChildCount];
var arr = new ItemFields[oldLen + 1];
dtoOptions.Fields.CopyTo(arr, 0);
arr[oldLen] = ItemFields.ChildCount;
dtoOptions.Fields = arr;
} }
} }

View File

@ -1779,14 +1779,11 @@ namespace MediaBrowser.Controller.Entities
int curLen = current.Length; int curLen = current.Length;
if (curLen == 0) if (curLen == 0)
{ {
Studios = new[] { name }; Studios = [name];
} }
else else
{ {
var newArr = new string[curLen + 1]; Studios = [..current, name];
current.CopyTo(newArr, 0);
newArr[curLen] = name;
Studios = newArr;
} }
} }
} }
@ -1808,9 +1805,7 @@ namespace MediaBrowser.Controller.Entities
var genres = Genres; var genres = Genres;
if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase)) if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase))
{ {
var list = genres.ToList(); Genres = [..genres, name];
list.Add(name);
Genres = list.ToArray();
} }
} }
@ -1980,12 +1975,7 @@ namespace MediaBrowser.Controller.Entities
public void AddImage(ItemImageInfo image) public void AddImage(ItemImageInfo image)
{ {
var current = ImageInfos; ImageInfos = [..ImageInfos, image];
var currentCount = current.Length;
var newArr = new ItemImageInfo[currentCount + 1];
current.CopyTo(newArr, 0);
newArr[currentCount] = image;
ImageInfos = newArr;
} }
public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken) public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)

View File

@ -30,15 +30,11 @@ namespace MediaBrowser.Controller.Entities
if (item.RemoteTrailers.Count == 0) if (item.RemoteTrailers.Count == 0)
{ {
item.RemoteTrailers = new[] { mediaUrl }; item.RemoteTrailers = [mediaUrl];
} }
else else
{ {
var oldIds = item.RemoteTrailers; item.RemoteTrailers = [..item.RemoteTrailers, mediaUrl];
var newIds = new MediaUrl[oldIds.Count + 1];
oldIds.CopyTo(newIds);
newIds[oldIds.Count] = mediaUrl;
item.RemoteTrailers = newIds;
} }
} }
} }

View File

@ -21,11 +21,11 @@ namespace MediaBrowser.Controller.Entities
{ {
if (current.Length == 0) if (current.Length == 0)
{ {
item.Tags = new[] { name }; item.Tags = [name];
} }
else else
{ {
item.Tags = current.Concat(new[] { name }).ToArray(); item.Tags = [..current, name];
} }
} }
} }

View File

@ -116,8 +116,8 @@ namespace MediaBrowser.Controller.Library
{ {
get get
{ {
var paths = string.IsNullOrEmpty(Path) ? Array.Empty<string>() : new[] { Path }; var paths = string.IsNullOrEmpty(Path) ? Array.Empty<string>() : [Path];
return AdditionalLocations is null ? paths : paths.Concat(AdditionalLocations).ToArray(); return AdditionalLocations is null ? paths : [..paths, ..AdditionalLocations];
} }
} }

View File

@ -288,7 +288,7 @@ namespace MediaBrowser.Controller.Net
lock (_activeConnectionsLock) lock (_activeConnectionsLock)
{ {
foreach (var connection in _activeConnections.ToArray()) foreach (var connection in _activeConnections.ToList())
{ {
DisposeConnection(connection); DisposeConnection(connection);
} }

View File

@ -270,9 +270,7 @@ namespace MediaBrowser.Controller.Session
public void AddController(ISessionController controller) public void AddController(ISessionController controller)
{ {
var controllers = SessionControllers.ToList(); SessionControllers = [..SessionControllers, controller];
controllers.Add(controller);
SessionControllers = controllers.ToArray();
} }
public bool ContainsUser(Guid userId) public bool ContainsUser(Guid userId)

View File

@ -117,9 +117,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
var artist = reader.ReadNormalizedString(); var artist = reader.ReadNormalizedString();
if (!string.IsNullOrEmpty(artist) && item is MusicVideo artistVideo) if (!string.IsNullOrEmpty(artist) && item is MusicVideo artistVideo)
{ {
var list = artistVideo.Artists.ToList(); artistVideo.Artists = [..artistVideo.Artists, artist];
list.Add(artist);
artistVideo.Artists = list.ToArray();
} }
break; break;

View File

@ -1130,7 +1130,7 @@ namespace Jellyfin.LiveTv.Channels
{ {
if (!item.Tags.Contains("livestream", StringComparison.OrdinalIgnoreCase)) if (!item.Tags.Contains("livestream", StringComparison.OrdinalIgnoreCase))
{ {
item.Tags = item.Tags.Concat(new[] { "livestream" }).ToArray(); item.Tags = [..item.Tags, "livestream"];
_logger.LogDebug("Forcing update due to Tags {0}", item.Name); _logger.LogDebug("Forcing update due to Tags {0}", item.Name);
forceUpdate = true; forceUpdate = true;
} }

View File

@ -60,14 +60,13 @@ public class ListingsManager : IListingsManager
var config = _config.GetLiveTvConfiguration(); var config = _config.GetLiveTvConfiguration();
var list = config.ListingProviders.ToList(); var list = config.ListingProviders;
int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); int index = Array.FindIndex(list, i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
if (index == -1 || string.IsNullOrWhiteSpace(info.Id)) if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
{ {
info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
list.Add(info); config.ListingProviders = [..list, info];
config.ListingProviders = list.ToArray();
} }
else else
{ {
@ -236,13 +235,12 @@ public class ListingsManager : IListingsManager
if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase)) if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase))
{ {
var list = listingsProviderInfo.ChannelMappings.ToList(); var newItem = new NameValuePair
list.Add(new NameValuePair
{ {
Name = tunerChannelNumber, Name = tunerChannelNumber,
Value = providerChannelNumber Value = providerChannelNumber
}); };
listingsProviderInfo.ChannelMappings = list.ToArray(); listingsProviderInfo.ChannelMappings = [..listingsProviderInfo.ChannelMappings, newItem];
} }
_config.SaveConfiguration("livetv", config); _config.SaveConfiguration("livetv", config);

View File

@ -939,7 +939,7 @@ namespace Jellyfin.LiveTv
{ {
var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId); var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
var channel = _libraryManager.GetItemById(internalChannelId); var channel = _libraryManager.GetItemById(internalChannelId);
channelName = channel is null ? null : channel.Name; channelName = channel?.Name;
} }
return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName); return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);

View File

@ -115,11 +115,7 @@ namespace Jellyfin.LiveTv.Timers
throw new ArgumentException("item already exists", nameof(item)); throw new ArgumentException("item already exists", nameof(item));
} }
int oldLen = _items.Length; _items = [.._items, item];
var newList = new T[oldLen + 1];
_items.CopyTo(newList, 0);
newList[oldLen] = item;
_items = newList;
SaveList(); SaveList();
} }
@ -134,11 +130,7 @@ namespace Jellyfin.LiveTv.Timers
int index = Array.FindIndex(_items, i => EqualityComparer(i, item)); int index = Array.FindIndex(_items, i => EqualityComparer(i, item));
if (index == -1) if (index == -1)
{ {
int oldLen = _items.Length; _items = [.._items, item];
var newList = new T[oldLen + 1];
_items.CopyTo(newList, 0);
newList[oldLen] = item;
_items = newList;
} }
else else
{ {

View File

@ -76,14 +76,13 @@ public class TunerHostManager : ITunerHostManager
var config = _config.GetLiveTvConfiguration(); var config = _config.GetLiveTvConfiguration();
var list = config.TunerHosts.ToList(); var list = config.TunerHosts;
var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); var index = Array.FindIndex(list, i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
if (index == -1 || string.IsNullOrWhiteSpace(info.Id)) if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
{ {
info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
list.Add(info); config.TunerHosts = [..list, info];
config.TunerHosts = list.ToArray();
} }
else else
{ {