Skip to content

Commit

Permalink
Optimize Guid comparisons
Browse files Browse the repository at this point in the history
* Use Guid.Equals(Guid) instead of the == override
* Ban the usage of Guid.Equals(Object) to prevent accidental boxing
* Compare to default(Guid) instead of Guid.Empty
  • Loading branch information
Bond-009 committed Feb 21, 2022
1 parent bbac59c commit f50a250
Show file tree
Hide file tree
Showing 66 changed files with 356 additions and 327 deletions.
3 changes: 3 additions & 0 deletions BannedSymbols.txt
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
P:System.Threading.Tasks.Task`1.Result
M:System.Guid.op_Equality(System.Guid,System.Guid)
M:System.Guid.op_Inequality(System.Guid,System.Guid)
M:System.Guid.Equals(System.Object)
4 changes: 2 additions & 2 deletions Emby.Dlna/Didl/DidlBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public void WriteItemElement(
else
{
var parent = item.DisplayParentId;
if (!parent.Equals(Guid.Empty))
if (!parent.Equals(default))
{
writer.WriteAttributeString("parentID", GetClientId(parent, null));
}
Expand Down Expand Up @@ -657,7 +657,7 @@ public void WriteFolderElement(XmlWriter writer, BaseItem folder, StubType? stub
else
{
var parent = folder.DisplayParentId;
if (parent.Equals(Guid.Empty))
if (parent.Equals(default))
{
writer.WriteAttributeString("parentID", "0");
}
Expand Down
24 changes: 16 additions & 8 deletions Emby.Dlna/PlayTo/PlayToController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ private async void OnDeviceMediaChanged(object sender, MediaChangedEventArgs e)
await _sessionManager.OnPlaybackStart(newItemProgress).ConfigureAwait(false);

// Send a message to the DLNA device to notify what is the next track in the playlist.
var currentItemIndex = _playlist.FindIndex(item => item.StreamInfo.ItemId == streamInfo.ItemId);
var currentItemIndex = _playlist.FindIndex(item => item.StreamInfo.ItemId.Equals(streamInfo.ItemId));
if (currentItemIndex >= 0)
{
_currentPlaylistIndex = currentItemIndex;
Expand Down Expand Up @@ -349,7 +349,9 @@ public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationT
{
_logger.LogDebug("{0} - Received PlayRequest: {1}", _session.DeviceName, command.PlayCommand);

var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId);
var user = command.ControllingUserId.Equals(default)
? null :
_userManager.GetUserById(command.ControllingUserId);

var items = new List<BaseItem>();
foreach (var id in command.ItemIds)
Expand Down Expand Up @@ -392,7 +394,7 @@ public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationT
_playlist.AddRange(playlist);
}

if (!command.ControllingUserId.Equals(Guid.Empty))
if (!command.ControllingUserId.Equals(default))
{
_sessionManager.LogSessionActivity(
_session.Client,
Expand Down Expand Up @@ -446,7 +448,9 @@ private async Task Seek(long newPosition)

if (info.Item != null && !EnableClientSideSeek(info))
{
var user = !_session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(_session.UserId) : null;
var user = _session.UserId.Equals(default)
? null
: _userManager.GetUserById(_session.UserId);
var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, info.AudioStreamIndex, info.SubtitleStreamIndex);

await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false);
Expand Down Expand Up @@ -764,7 +768,9 @@ private async Task SetAudioStreamIndex(int? newIndex)
{
var newPosition = GetProgressPositionTicks(info) ?? 0;

var user = !_session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(_session.UserId) : null;
var user = _session.UserId.Equals(default)
? null
: _userManager.GetUserById(_session.UserId);
var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, newIndex, info.SubtitleStreamIndex);

await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false);
Expand Down Expand Up @@ -793,7 +799,9 @@ private async Task SetSubtitleStreamIndex(int? newIndex)
{
var newPosition = GetProgressPositionTicks(info) ?? 0;

var user = !_session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(_session.UserId) : null;
var user = _session.UserId.Equals(default)
? null
: _userManager.GetUserById(_session.UserId);
var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, info.AudioStreamIndex, newIndex);

await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false);
Expand Down Expand Up @@ -949,7 +957,7 @@ private static Guid GetItemId(string url)
}
}

return Guid.Empty;
return default;
}

public static StreamParams ParseFromUrl(string url, ILibraryManager libraryManager, IMediaSourceManager mediaSourceManager)
Expand All @@ -964,7 +972,7 @@ public static StreamParams ParseFromUrl(string url, ILibraryManager libraryManag
ItemId = GetItemId(url)
};

if (request.ItemId.Equals(Guid.Empty))
if (request.ItemId.Equals(default))
{
return request;
}
Expand Down
2 changes: 1 addition & 1 deletion Emby.Notifications/NotificationEntryPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ private async void OnActivityManagerEntryCreated(object? sender, GenericEventArg

var userId = e.Argument.UserId;

if (!userId.Equals(Guid.Empty) && !GetOptions().IsEnabledToMonitorUser(type, userId))
if (!userId.Equals(default) && !GetOptions().IsEnabledToMonitorUser(type, userId))
{
return;
}
Expand Down
12 changes: 7 additions & 5 deletions Emby.Server.Implementations/Channels/ChannelManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public IEnumerable<Guid> GetInstalledChannelIds()
/// <inheritdoc />
public QueryResult<Channel> GetChannelsInternal(ChannelQuery query)
{
var user = query.UserId.Equals(Guid.Empty)
var user = query.UserId.Equals(default)
? null
: _userManager.GetUserById(query.UserId);

Expand Down Expand Up @@ -274,7 +274,7 @@ public QueryResult<Channel> GetChannelsInternal(ChannelQuery query)
/// <inheritdoc />
public QueryResult<BaseItemDto> GetChannels(ChannelQuery query)
{
var user = query.UserId.Equals(Guid.Empty)
var user = query.UserId.Equals(default)
? null
: _userManager.GetUserById(query.UserId);

Expand Down Expand Up @@ -474,7 +474,7 @@ private async Task<Channel> GetChannel(IChannel channelInfo, CancellationToken c

item.ChannelId = id;

if (item.ParentId != parentFolderId)
if (!item.ParentId.Equals(parentFolderId))
{
forceUpdate = true;
}
Expand Down Expand Up @@ -715,7 +715,9 @@ public async Task<QueryResult<BaseItem>> GetChannelItemsInternal(InternalItemsQu
// Find the corresponding channel provider plugin
var channelProvider = GetChannelProvider(channel);

var parentItem = query.ParentId == Guid.Empty ? channel : _libraryManager.GetItemById(query.ParentId);
var parentItem = query.ParentId.Equals(default)
? channel
: _libraryManager.GetItemById(query.ParentId);

var itemsResult = await GetChannelItems(
channelProvider,
Expand All @@ -726,7 +728,7 @@ public async Task<QueryResult<BaseItem>> GetChannelItemsInternal(InternalItemsQu
cancellationToken)
.ConfigureAwait(false);

if (query.ParentId == Guid.Empty)
if (query.ParentId.Equals(default))
{
query.Parent = channel;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ public async Task RemoveFromCollectionAsync(Guid collectionId, IEnumerable<Guid>
{
var childItem = _libraryManager.GetItemById(guidId);

var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value.Equals(guidId)) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));

if (child == null)
{
Expand Down
6 changes: 3 additions & 3 deletions Emby.Server.Implementations/Dto/DtoService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1308,7 +1308,7 @@ private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions optio

var allImages = parent.ImageInfos;

if (logoLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId == null)
if (logoLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId is null)
{
var image = allImages.FirstOrDefault(i => i.Type == ImageType.Logo);

Expand All @@ -1319,7 +1319,7 @@ private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions optio
}
}

if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId == null)
if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId is null)
{
var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);

Expand All @@ -1330,7 +1330,7 @@ private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions optio
}
}

if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && parent is not ICollectionFolder && parent is not UserView)
if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId is null || parent is Series) && parent is not ICollectionFolder && parent is not UserView)
{
var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ private async Task SendChangeNotifications(List<BaseItem> itemsAdded, List<BaseI
{
var userIds = _sessionManager.Sessions
.Select(i => i.UserId)
.Where(i => !i.Equals(Guid.Empty))
.Where(i => !i.Equals(default))
.Distinct()
.ToArray();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ public Task<SessionInfo> GetSession(object requestContext)
{
var session = await GetSession(requestContext).ConfigureAwait(false);

return session.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(session.UserId);
return session.UserId.Equals(default)
? null
: _userManager.GetUserById(session.UserId);
}

public Task<User?> GetUser(object requestContext)
Expand Down
34 changes: 19 additions & 15 deletions Emby.Server.Implementations/Library/LibraryManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@ public AggregateFolder CreateRootFolder()
Path = path
};

if (folder.Id.Equals(Guid.Empty))
if (folder.Id.Equals(default))
{
if (string.IsNullOrEmpty(folder.Path))
{
Expand All @@ -774,7 +774,7 @@ public AggregateFolder CreateRootFolder()
folder = dbItem;
}

if (folder.ParentId != rootFolder.Id)
if (!folder.ParentId.Equals(rootFolder.Id))
{
folder.ParentId = rootFolder.Id;
folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
Expand Down Expand Up @@ -1252,7 +1252,7 @@ private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCol
/// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception>
public BaseItem GetItemById(Guid id)
{
if (id == Guid.Empty)
if (id.Equals(default))
{
throw new ArgumentException("Guid can't be empty", nameof(id));
}
Expand All @@ -1274,7 +1274,7 @@ public BaseItem GetItemById(Guid id)

public List<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
{
if (query.Recursive && query.ParentId != Guid.Empty)
if (query.Recursive && !query.ParentId.Equals(default))
{
var parent = GetItemById(query.ParentId);
if (parent != null)
Expand All @@ -1298,7 +1298,7 @@ public List<BaseItem> GetItemList(InternalItemsQuery query)

public int GetCount(InternalItemsQuery query)
{
if (query.Recursive && !query.ParentId.Equals(Guid.Empty))
if (query.Recursive && !query.ParentId.Equals(default))
{
var parent = GetItemById(query.ParentId);
if (parent != null)
Expand Down Expand Up @@ -1456,7 +1456,7 @@ private void SetTopParentOrAncestorIds(InternalItemsQuery query)

public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
{
if (query.Recursive && !query.ParentId.Equals(Guid.Empty))
if (query.Recursive && !query.ParentId.Equals(default))
{
var parent = GetItemById(query.ParentId);
if (parent != null)
Expand Down Expand Up @@ -1512,7 +1512,7 @@ private void SetTopParentIdsOrAncestors(InternalItemsQuery query, List<BaseItem>
private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
{
if (query.AncestorIds.Length == 0 &&
query.ParentId.Equals(Guid.Empty) &&
query.ParentId.Equals(default) &&
query.ChannelIds.Count == 0 &&
query.TopParentIds.Length == 0 &&
string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
Expand Down Expand Up @@ -1540,7 +1540,7 @@ private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User user)
}

// Translate view into folders
if (!view.DisplayParentId.Equals(Guid.Empty))
if (!view.DisplayParentId.Equals(default))
{
var displayParent = GetItemById(view.DisplayParentId);
if (displayParent != null)
Expand All @@ -1551,7 +1551,7 @@ private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User user)
return Array.Empty<Guid>();
}

if (!view.ParentId.Equals(Guid.Empty))
if (!view.ParentId.Equals(default))
{
var displayParent = GetItemById(view.ParentId);
if (displayParent != null)
Expand Down Expand Up @@ -2153,7 +2153,7 @@ private string GetTopFolderContentType(BaseItem item)
return null;
}

while (!item.ParentId.Equals(Guid.Empty))
while (!item.ParentId.Equals(default))
{
var parent = item.GetParent();
if (parent == null || parent is AggregateFolder)
Expand Down Expand Up @@ -2231,7 +2231,9 @@ public UserView GetNamedView(
string viewType,
string sortName)
{
var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
var parentIdString = parentId.Equals(default)
? null
: parentId.ToString("N", CultureInfo.InvariantCulture);
var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);

var id = GetNewItemId(idValues, typeof(UserView));
Expand Down Expand Up @@ -2265,7 +2267,7 @@ public UserView GetNamedView(

var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;

if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
if (!refresh && !item.DisplayParentId.Equals(default))
{
var displayParent = GetItemById(item.DisplayParentId);
refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
Expand Down Expand Up @@ -2332,7 +2334,7 @@ public UserView GetShadowView(

var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;

if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
if (!refresh && !item.DisplayParentId.Equals(default))
{
var displayParent = GetItemById(item.DisplayParentId);
refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
Expand Down Expand Up @@ -2365,7 +2367,9 @@ public UserView GetNamedView(
throw new ArgumentNullException(nameof(name));
}

var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
var parentIdString = parentId.Equals(default)
? null
: parentId.ToString("N", CultureInfo.InvariantCulture);
var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
if (!string.IsNullOrEmpty(uniqueId))
{
Expand Down Expand Up @@ -2409,7 +2413,7 @@ public UserView GetNamedView(

var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;

if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
if (!refresh && !item.DisplayParentId.Equals(default))
{
var displayParent = GetItemById(item.DisplayParentId);
refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
Expand Down
4 changes: 2 additions & 2 deletions Emby.Server.Implementations/Library/MediaSourceManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -514,10 +514,10 @@ public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStre
_logger.LogInformation("Live stream opened: {@MediaSource}", mediaSource);
var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, _jsonOptions);

if (!request.UserId.Equals(Guid.Empty))
if (!request.UserId.Equals(default))
{
var user = _userManager.GetUserById(request.UserId);
var item = request.ItemId.Equals(Guid.Empty)
var item = request.ItemId.Equals(default)
? null
: _libraryManager.GetItemById(request.ItemId);
SetDefaultAudioAndSubtitleStreamIndexes(item, clone, user);
Expand Down
2 changes: 1 addition & 1 deletion Emby.Server.Implementations/Library/MusicManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public List<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User u
{
return Guid.Empty;
}
}).Where(i => !i.Equals(Guid.Empty)).ToArray();
}).Where(i => !i.Equals(default)).ToArray();

return GetInstantMixFromGenreIds(genreIds, user, dtoOptions);
}
Expand Down
Loading

0 comments on commit f50a250

Please sign in to comment.