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

Remove char[] allocations from RegistryKey and List copy to Array #78737

Merged
merged 3 commits into from
Dec 5, 2022
Merged
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -784,24 +784,24 @@ public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView vie
/// <returns>All subkey names.</returns>
public string[] GetSubKeyNames()
{
EnsureNotDisposed();
int subkeys = SubKeyCount;

if (subkeys <= 0)
{
return Array.Empty<string>();
}

List<string> names = new List<string>(subkeys);
Span<char> name = stackalloc char[MaxKeyLength + 1];
string[] names = new string[subkeys];
Span<char> nameSpan = stackalloc char[MaxKeyLength + 1];

int result;
int nameLength = name.Length;
int nameLength = nameSpan.Length;
int cpt = 0;

while ((result = Interop.Advapi32.RegEnumKeyEx(
_hkey,
names.Count,
ref MemoryMarshal.GetReference(name),
cpt,
ref MemoryMarshal.GetReference(nameSpan),
ref nameLength,
null,
null,
Expand All @@ -811,17 +811,29 @@ ref MemoryMarshal.GetReference(name),
switch (result)
{
case Interop.Errors.ERROR_SUCCESS:
names.Add(new string(name.Slice(0, nameLength)));
nameLength = name.Length;
if (cpt >= names.Length) // possible new item during loop
{
Array.Resize(ref names, names.Length * 2);
}

names[cpt++] = new string(nameSpan.Slice(0, nameLength));
nameLength = nameSpan.Length;
break;
stephentoub marked this conversation as resolved.
Show resolved Hide resolved

default:
// Throw the error
Win32Error(result, null);
break;
}
}

return names.ToArray();
// Shrink array to fit found items, if necessary
if (cpt < names.Length)
{
Array.Resize(ref names, cpt);
}

return names;
}

/// <summary>Retrieves the count of values.</summary>
Expand Down Expand Up @@ -858,8 +870,6 @@ public int ValueCount
/// <returns>All value names.</returns>
public unsafe string[] GetValueNames()
{
EnsureNotDisposed();

int values = ValueCount;

if (values <= 0)
Expand Down