From 73788d73053ed04117aea10751962920787e4670 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sat, 11 Jan 2020 13:30:17 +0100 Subject: [PATCH] ls: Cache the user and group names instead of looking up every time --- Userland/ls.cpp | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Userland/ls.cpp b/Userland/ls.cpp index 8adad40aea..76cbaebd7a 100644 --- a/Userland/ls.cpp +++ b/Userland/ls.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -32,6 +33,9 @@ static size_t terminal_rows = 0; static size_t terminal_columns = 0; static bool output_is_terminal = false; +static HashMap users; +static HashMap groups; + int main(int argc, char** argv) { struct winsize ws; @@ -76,6 +80,17 @@ int main(int argc, char** argv) } } + if (flag_long) { + setpwent(); + for (auto* pwd = getpwent(); pwd; pwd = getpwent()) + users.set(pwd->pw_uid, pwd->pw_name); + endpwent(); + setgrent(); + for (auto* grp = getgrent(); grp; grp = getgrent()) + groups.set(grp->gr_gid, grp->gr_name); + endgrent(); + } + auto do_file_system_object = [&](const char* path) { if (flag_long) return do_file_system_object_long(path); @@ -196,15 +211,15 @@ bool print_filesystem_object(const String& path, const String& name, const struc else printf("%c", st.st_mode & S_IXOTH ? 'x' : '-'); - passwd* pwd = getpwuid(st.st_uid); - group* grp = getgrgid(st.st_gid); - if (!flag_print_numeric && pwd) { - printf(" %7s", pwd->pw_name); + auto username = users.get(st.st_uid); + auto groupname = groups.get(st.st_gid); + if (!flag_print_numeric && username.has_value()) { + printf(" %7s", username.value().characters()); } else { printf(" %7u", st.st_uid); } - if (!flag_print_numeric && grp) { - printf(" %7s", grp->gr_name); + if (!flag_print_numeric && groupname.has_value()) { + printf(" %7s", groupname.value().characters()); } else { printf(" %7u", st.st_gid); }