lib/fs: Optimize WindowsInvalidFilename (#8687)

Replaced strings.Split with the new strings.Cut, which doesn't allocate.

name                           old time/op    new time/op    delta
WindowsInvalidFilenameValid-8     154ns ± 2%      89ns ± 0%   -42.09%  (p=0.000 n=10+9)
WindowsInvalidFilenameNUL-8       124ns ± 2%     124ns ± 1%      ~     (p=0.371 n=8+10)

name                           old alloc/op   new alloc/op   delta
WindowsInvalidFilenameValid-8     16.0B ± 0%      0.0B       -100.00%  (p=0.000 n=10+10)
WindowsInvalidFilenameNUL-8       19.0B ± 0%      3.0B ± 0%   -84.21%  (p=0.000 n=10+10)

name                           old allocs/op  new allocs/op  delta
WindowsInvalidFilenameValid-8      1.00 ± 0%      0.00       -100.00%  (p=0.000 n=10+10)
WindowsInvalidFilenameNUL-8        2.00 ± 0%      1.00 ± 0%   -50.00%  (p=0.000 n=10+10)
This commit is contained in:
greatroar 2022-11-21 12:58:00 +01:00 committed by GitHub
parent 0b2b8baf19
commit 663106ef6e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -53,9 +53,17 @@ const windowsDisallowedCharacters = (`<>:"|?*` +
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f") "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f")
func WindowsInvalidFilename(name string) error { func WindowsInvalidFilename(name string) error {
// The path must not contain any disallowed characters.
if strings.ContainsAny(name, windowsDisallowedCharacters) {
return errInvalidFilenameWindowsReservedChar
}
// None of the path components should end in space or period, or be a // None of the path components should end in space or period, or be a
// reserved name. // reserved name.
for _, part := range strings.Split(name, `\`) { for len(name) > 0 {
part, rest, _ := strings.Cut(name, `\`)
name = rest
if part == "" { if part == "" {
continue continue
} }
@ -69,11 +77,6 @@ func WindowsInvalidFilename(name string) error {
} }
} }
// The path must not contain any disallowed characters
if strings.ContainsAny(name, windowsDisallowedCharacters) {
return errInvalidFilenameWindowsReservedChar
}
return nil return nil
} }