Skip to content

Commit 27ece42

Browse files
committed
Cache filename for sorting in fill_todo
1 parent 335da33 commit 27ece42

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/lib.rs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ doctest!("../README.md");
7373
use std::cmp;
7474
use std::cmp::Ordering;
7575
use std::error::Error;
76+
use std::ffi::OsString;
7677
use std::fmt;
7778
use std::fs;
7879
use std::fs::DirEntry;
@@ -945,24 +946,30 @@ fn fill_todo(
945946
let dirs = fs::read_dir(path).and_then(|d| {
946947
d.map(|e| {
947948
e.map(|e| {
948-
let path = if curdir {
949-
PathBuf::from(e.path().file_name().unwrap())
949+
// We sort by filename a few lines below. However, it is actually quite
950+
// expensive to extract the filename from PathBuf. Since we already know the
951+
// filename from `DirEntry` here, we store it proactively (we still
952+
// have to heap allocate it).
953+
// Then we use this cached filename for sorting, and further on work only
954+
// with the full path.
955+
let (path, filename) = if curdir {
956+
(PathBuf::from(e.path().file_name().unwrap()), e.file_name())
950957
} else {
951-
e.path()
958+
(e.path(), e.file_name())
952959
};
953-
PathWrapper::from_dir_entry(path, e)
960+
(PathWrapper::from_dir_entry(path, e), filename)
954961
})
955962
})
956-
.collect::<Result<Vec<_>, _>>()
963+
.collect::<Result<Vec<(PathWrapper, OsString)>, _>>()
957964
});
958965
match dirs {
959966
Ok(mut children) => {
960967
if options.require_literal_leading_dot {
961968
children
962-
.retain(|x| !x.file_name().unwrap().to_str().unwrap().starts_with('.'));
969+
.retain(|x| !x.0.file_name().unwrap().to_str().unwrap().starts_with('.'));
963970
}
964-
children.sort_by(|p1, p2| p2.file_name().cmp(&p1.file_name()));
965-
todo.extend(children.into_iter().map(|x| Ok((x, idx))));
971+
children.sort_by(|p1, p2| p2.1.cmp(&p1.1));
972+
todo.extend(children.into_iter().map(|x| Ok((x.0, idx))));
966973

967974
// Matching the special directory entries . and .. that
968975
// refer to the current and parent directory respectively

0 commit comments

Comments
 (0)