Skip to content

Commit

Permalink
Make FileInfo/DirectoryInfo.Name lazy (#73983)
Browse files Browse the repository at this point in the history
We can delay the string allocation until it's actually requested.
  • Loading branch information
stephentoub authored Aug 17, 2022
1 parent 3494c39 commit 96d1c8e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,30 @@ private void Init(string originalPath, string? fullPath = null, string? fileName
fullPath ??= originalPath;
fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath);

_name = fileName ?? (PathInternal.IsRoot(fullPath.AsSpan()) ?
fullPath.AsSpan() :
Path.GetFileName(Path.TrimEndingDirectorySeparator(fullPath.AsSpan()))).ToString();
_name = fileName;

FullPath = fullPath;

_isNormalized = isNormalized;
}

public override string Name
{
get
{
string? name = _name;
if (name is null)
{
ReadOnlySpan<char> fullPath = FullPath.AsSpan();
_name = name = (PathInternal.IsRoot(fullPath) ?
fullPath :
Path.GetFileName(Path.TrimEndingDirectorySeparator(fullPath))).ToString();
}

return name;
}
}

public DirectoryInfo? Parent
{
get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@ internal FileInfo(string originalPath, string? fullPath = null, string? fileName
Debug.Assert(!isNormalized || !PathInternal.IsPartiallyQualified(fullPath.AsSpan()), "should be fully qualified if normalized");

FullPath = isNormalized ? fullPath ?? originalPath : Path.GetFullPath(fullPath);
_name = fileName ?? Path.GetFileName(originalPath);
_name = fileName;
}

public override string Name => _name ??= Path.GetFileName(OriginalPath);

public long Length
{
get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
Expand All @@ -14,7 +15,7 @@ public abstract partial class FileSystemInfo : MarshalByRefObject, ISerializable
protected string FullPath = null!; // fully qualified path of the file or directory
protected string OriginalPath = null!; // path passed in by the user

internal string _name = null!; // Fields initiated in derived classes
internal string? _name;

private string? _linkTarget;
private bool _linkTargetIsValid;
Expand Down Expand Up @@ -55,7 +56,14 @@ public string Extension
}
}

public virtual string Name => _name;
public virtual string Name
{
get
{
Debug.Fail("Property is abstract in the ref assembly and both Directory/FileInfo override it.");
return _name!;
}
}

// Whether a file/directory exists
public virtual bool Exists
Expand Down

0 comments on commit 96d1c8e

Please sign in to comment.