[go: up one dir, main page]

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

Minor changes to reduce allocations #848

Merged
merged 12 commits into from
Feb 20, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Less string allocations
  • Loading branch information
Bond-009 committed Feb 12, 2019
commit 8d98885cdae15cc9865e0984e4270ee4a8d9d2db
33 changes: 16 additions & 17 deletions Emby.Server.Implementations/HttpServer/HttpResultFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public object GetRedirectResult(string url)
/// </summary>
private IHasHeaders GetHttpResult(IRequest requestContext, Stream content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
{
var result = new StreamWriter(content, contentType, _logger);
var result = new StreamWriter(content, contentType);

if (responseHeaders == null)
{
Expand Down Expand Up @@ -131,7 +131,7 @@ private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, strin
content = Array.Empty<byte>();
}

result = new StreamWriter(content, contentType, contentLength, _logger);
result = new StreamWriter(content, contentType, contentLength);
}
else
{
Expand All @@ -143,7 +143,7 @@ private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, strin
responseHeaders = new Dictionary<string, string>();
}

if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires))
if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
{
responseHeaders["Expires"] = "-1";
}
Expand Down Expand Up @@ -175,7 +175,7 @@ private IHasHeaders GetHttpResult(IRequest requestContext, string content, strin
bytes = Array.Empty<byte>();
}

result = new StreamWriter(bytes, contentType, contentLength, _logger);
result = new StreamWriter(bytes, contentType, contentLength);
}
else
{
Expand All @@ -187,7 +187,7 @@ private IHasHeaders GetHttpResult(IRequest requestContext, string content, strin
responseHeaders = new Dictionary<string, string>();
}

if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires))
if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
{
responseHeaders["Expires"] = "-1";
}
Expand Down Expand Up @@ -277,9 +277,9 @@ public object ToOptimizedResult<T>(IRequest request, T dto)

private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
{
var contentType = request.ResponseContentType;
var contentType = request.ResponseContentType?.Split(';')[0];
JustAMan marked this conversation as resolved.
Show resolved Hide resolved

switch (GetRealContentType(contentType))
switch (contentType)
{
case "application/xml":
case "text/xml":
Expand Down Expand Up @@ -333,13 +333,13 @@ private IHasHeaders GetCompressedResult(byte[] content,

if (isHeadRequest)
{
var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength, _logger);
var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
AddResponseHeaders(result, responseHeaders);
return result;
}
else
{
var result = new StreamWriter(content, contentType, contentLength, _logger);
var result = new StreamWriter(content, contentType, contentLength);
AddResponseHeaders(result, responseHeaders);
return result;
}
Expand All @@ -348,13 +348,19 @@ private IHasHeaders GetCompressedResult(byte[] content,
private byte[] Compress(byte[] bytes, string compressionType)
{
if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
JustAMan marked this conversation as resolved.
Show resolved Hide resolved
{
return CompressBrotli(bytes);
}

if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
{
return Deflate(bytes);
}

if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
{
return GZip(bytes);
}

throw new NotSupportedException(compressionType);
}
Expand Down Expand Up @@ -390,13 +396,6 @@ private static byte[] GZip(byte[] buffer)
}
}

public static string GetRealContentType(string contentType)
{
return contentType == null
? null
: contentType.Split(';')[0].ToLowerInvariant().Trim();
}

private static string SerializeToXmlString(object from)
{
using (var ms = new MemoryStream())
Expand Down Expand Up @@ -621,7 +620,7 @@ public async Task<object> GetStaticResult(IRequest requestContext, StaticResultO
}
}

var hasHeaders = new StreamWriter(stream, contentType, _logger)
var hasHeaders = new StreamWriter(stream, contentType)
{
>
>
Expand Down
8 changes: 2 additions & 6 deletions Emby.Server.Implementations/HttpServer/StreamWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ namespace Emby.Server.Implementations.HttpServer
/// </summary>
public class StreamWriter : IAsyncStreamWriter, IHasHeaders
{
private ILogger Logger { get; set; }

private static readonly CultureInfo UsCulture = new CultureInfo("en-US");

/// <summary>
Expand Down Expand Up @@ -45,15 +43,14 @@ public class StreamWriter : IAsyncStreamWriter, IHasHeaders
/// <param name="source">The source.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="logger">The logger.</param>
public StreamWriter(Stream source, string contentType, ILogger logger)
public StreamWriter(Stream source, string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
throw new ArgumentNullException(nameof(contentType));
}

SourceStream = source;
Logger = logger;

Headers["Content-Type"] = contentType;

Expand All @@ -69,15 +66,14 @@ public StreamWriter(Stream source, string contentType, ILogger logger)
/// <param name="source">The source.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="logger">The logger.</param>
public StreamWriter(byte[] source, string contentType, int contentLength, ILogger logger)
public StreamWriter(byte[] source, string contentType, int contentLength)
{
if (string.IsNullOrEmpty(contentType))
{
throw new ArgumentNullException(nameof(contentType));
}

SourceBytes = source;
Logger = logger;

Headers["Content-Type"] = contentType;

Expand Down
2 changes: 1 addition & 1 deletion Emby.Server.Implementations/LiveTv/LiveTvManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ public Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, Cancellatio

public QueryResult<BaseItem> GetInternalChannels(LiveTvChannelQuery query, DtoOptions dtoOptions, CancellationToken cancellationToken)
{
var user = query.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(query.UserId);
var user = query.UserId == Guid.Empty ? null : _userManager.GetUserById(query.UserId);

var topFolder = GetInternalLiveTvFolder(cancellationToken);

Expand Down
21 changes: 21 additions & 0 deletions Emby.Server.Implementations/Serialization/JsonSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,27 @@ public void SerializeToStream(object obj, Stream stream)
ServiceStack.Text.JsonSerializer.SerializeToStream(obj, obj.GetType(), stream);
}

/// <summary>
/// Serializes to stream.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="stream">The stream.</param>
/// <exception cref="ArgumentNullException">obj</exception>
public void SerializeToStream<T>(T obj, Stream stream)
JustAMan marked this conversation as resolved.
Show resolved Hide resolved
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}

if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}

ServiceStack.Text.JsonSerializer.SerializeToStream<T>(obj, stream);
}

/// <summary>
/// Serializes to file.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion Jellyfin.Server/Jellyfin.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<AssemblyName>jellyfin</AssemblyName>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFrameworks>netcoreapp2.2;netcoreapp3.0</TargetFrameworks>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>

Expand Down
30 changes: 23 additions & 7 deletions Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ internal static string CheckBadChars(string name)
name = name.Trim(HttpTrimCharacters);

// First, check for correctly formed multi-line value
// Second, check for absenece of CTL characters
// Second, check for absence of CTL characters
int crlf = 0;
for (int i = 0; i < name.Length; ++i)
{
Expand Down Expand Up @@ -216,8 +216,13 @@ public static string GetResponseContentType(IRequest httpReq)
{
foreach (var acceptsType in acceptContentTypes)
{
var contentType = HttpResultFactory.GetRealContentType(acceptsType);
acceptsAnything = acceptsAnything || contentType == "*/*";
var contentType = acceptsType?.Split(';')[0];
acceptsAnything = contentType.IndexOf("*/*", StringComparison.Ordinal) != -1;

if (acceptsAnything)
{
break;
}
}

if (acceptsAnything)
Expand All @@ -226,7 +231,7 @@ public static string GetResponseContentType(IRequest httpReq)
{
return defaultContentType;
}
else if (serverDefaultContentType != null)
else
JustAMan marked this conversation as resolved.
Show resolved Hide resolved
{
return serverDefaultContentType;
}
Expand Down Expand Up @@ -269,19 +274,19 @@ public static bool IsContentType(IRequest request, string contentType)

private static string GetQueryStringContentType(IRequest httpReq)
{
var format = httpReq.QueryString["format"];
ReadOnlySpan<char> format = httpReq.QueryString["format"];
if (format == null)
{
const int formatMaxLength = 4;
var pi = httpReq.PathInfo;
ReadOnlySpan<char> pi = httpReq.PathInfo;
if (pi == null || pi.Length <= formatMaxLength)
{
return null;
}

if (pi[0] == '/')
{
pi = pi.Substring(1);
pi = pi.Slice(1);
}

format = LeftPart(pi, '/');
Expand Down Expand Up @@ -315,6 +320,17 @@ public static string LeftPart(string strVal, char needle)
return pos == -1 ? strVal : strVal.Substring(0, pos);
}

public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
{
if (strVal == null)
{
return null;
}

var pos = strVal.IndexOf(needle);
return pos == -1 ? strVal : strVal.Slice(0, pos);
}

public static string HandlerFactoryPath;

private string pathInfo;
Expand Down
8 changes: 4 additions & 4 deletions MediaBrowser.Api/UserLibrary/ItemsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public object Get(GetResumeItems request)

var options = GetDtoOptions(_authContext, request);

var ancestorIds = new List<Guid>();
var ancestorIds = Array.Empty<Guid>();

var excludeFolderIds = user.Configuration.LatestItemsExcludes;
if (parentIdGuid.Equals(Guid.Empty) && excludeFolderIds.Length > 0)
Expand All @@ -99,12 +99,12 @@ public object Get(GetResumeItems request)
.Where(i => i is Folder)
.Where(i => !excludeFolderIds.Contains(i.Id.ToString("N")))
.Select(i => i.Id)
.ToList();
.ToArray();
}

var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
{
OrderBy = new[] { ItemSortBy.DatePlayed }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray(),
OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
IsResumable = true,
StartIndex = request.StartIndex,
Limit = request.Limit,
Expand All @@ -115,7 +115,7 @@ public object Get(GetResumeItems request)
IsVirtualItem = false,
CollapseBoxSetItems = false,
EnableTotalRecordCount = request.EnableTotalRecordCount,
AncestorIds = ancestorIds.ToArray(),
AncestorIds = ancestorIds,
IncludeItemTypes = request.GetIncludeItemTypes(),
ExcludeItemTypes = request.GetExcludeItemTypes(),
SearchTerm = request.SearchTerm
Expand Down
8 changes: 8 additions & 0 deletions MediaBrowser.Model/Serialization/IJsonSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ public interface IJsonSerializer
/// <exception cref="ArgumentNullException">obj</exception>
void SerializeToStream(object obj, Stream stream);

/// <summary>
/// Serializes to stream.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="stream">The stream.</param>
/// <exception cref="ArgumentNullException">obj</exception>
void SerializeToStream<T>(T obj, Stream stream);

/// <summary>
/// Serializes to file.
/// </summary>
Expand Down