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

Improve performance of JoinParts for spans #42

Merged
merged 6 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
54 changes: 54 additions & 0 deletions src/NexusMods.Paths.Benchmarks/Benchmarks/Pr42.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using NexusMods.Paths.Benchmarks.Interfaces;
using NexusMods.Paths.Utilities;

namespace NexusMods.Paths.Benchmarks.Benchmarks;

[BenchmarkInfo("PR42", "Comparison for PR #42")]
[MemoryDiagnoser]
public class Pr42 : IBenchmark
{
[Params(@"short", @"a/very/long/path/indeed/to/see/how/it/performs")]
public string Path1 { get; set; } = null!;

[Params("short", "a/very/long/path/indeed/to/see/how/it/performs")]
public string Path2 { get; set; } = null!;

private readonly IOSInformation _osInformation;

public Pr42()
{
_osInformation = OSInformation.Shared;
}

[Benchmark]
public string Current()
{
return PathHelpers.JoinParts(Path1.AsSpan(), Path2.AsSpan(), _osInformation);
}

[Benchmark]
public string OldMethod()
{
return JoinParts(Path1.AsSpan(), Path2.AsSpan(), _osInformation);
}

[SkipLocalsInit] // original method didn't have it, but it's still good for comparison.
private static string JoinParts(ReadOnlySpan<char> left, ReadOnlySpan<char> right, IOSInformation os)
{
var spanLength = PathHelpers.GetExactJoinedPartLength(left, right);
var buffer = spanLength > 512
? GC.AllocateUninitializedArray<char>(spanLength)
: stackalloc char[spanLength];

var count = PathHelpers.JoinParts(buffer, left, right, os);
if (count == 0) return string.Empty;
return buffer.ToString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
Expand Down
39 changes: 32 additions & 7 deletions src/NexusMods.Paths/Utilities/PathHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Reloaded.Memory.Extensions;
using Reloaded.Memory.Pointers;

namespace NexusMods.Paths.Utilities;

Expand Down Expand Up @@ -367,6 +368,7 @@ public static int JoinParts(Span<char> buffer, ReadOnlySpan<char> left, ReadOnly
return left.Length + DirectorySeparatorString.Length + right.Length;
}

#pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type
/// <summary>
/// Joins two path parts together and returns the joined path as a string.
/// </summary>
Expand All @@ -386,16 +388,39 @@ public static string JoinParts(ReadOnlySpan<char> left, ReadOnlySpan<char> right
DebugAssertIsSanitized(right, os);

var spanLength = GetExactJoinedPartLength(left, right);
var buffer = spanLength > 512
? GC.AllocateUninitializedArray<char>(spanLength)
: stackalloc char[spanLength];
unsafe
{
// Note: The two Span objects are on the Stack. We access them inside
// string.Create, by dereferencing these items from the stack.

// If a GC happens, the pointers inside these referenced items will be
// moved, but our stack objects won't. Therefore, access like this without
// an explicit pin is safe.
// A similar trick also exists out there known as 'ref pinning'.

// Don't believe me? Go crazy with `DOTNET_GCStress` 😉 - Sewer
var @params = new JoinPartsParams
{
Left = &left,
Right = &right,
Os = os
};

var count = JoinParts(buffer, left, right, os);
if (count == 0) return string.Empty;
return string.Create(spanLength, @params, (span, tuple) =>
{
var count = JoinParts(span, *tuple.Left, *tuple.Right, tuple.Os);
Debug.Assert(count == spanLength, $"Calculated span length '{spanLength}' doesn't match actual span length '{count}'");
});
}
}

Debug.Assert(count == spanLength, $"Calculated span length '{spanLength}' doesn't match actual span length '{count}'");
return buffer.ToString();
unsafe struct JoinPartsParams
{
internal ReadOnlySpan<char>* Left;
internal ReadOnlySpan<char>* Right;
internal IOSInformation Os;
}
#pragma warning restore CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type

/// <summary>
/// Joins two path parts together and returns the joined path as a string.
Expand Down
Loading