basic/terminal-util: cache value for colors_enabled
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Wed, 20 Apr 2016 01:30:14 +0000 (21:30 -0400)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Wed, 20 Apr 2016 12:58:53 +0000 (08:58 -0400)
After all it's something that we query over and over.
For example, systemctl calls colors_enabled() four times for each failing
service. The compiler is unable to optimize those calls away because they
(potentially) accesses external and global state through on_tty() and
getenv().

src/basic/terminal-util.c

index 0a9d2bb..9521b79 100644 (file)
@@ -1135,14 +1135,19 @@ int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
 }
 
 bool colors_enabled(void) {
-        const char *colors;
+        static int enabled = -1;
 
-        colors = getenv("SYSTEMD_COLORS");
-        if (!colors) {
-                if (streq_ptr(getenv("TERM"), "dumb"))
-                        return false;
-                return on_tty();
+        if (_unlikely_(enabled < 0)) {
+                const char *colors;
+
+                colors = getenv("SYSTEMD_COLORS");
+                if (colors)
+                        enabled = parse_boolean(colors) != 0;
+                else if (streq_ptr(getenv("TERM"), "dumb"))
+                        enabled = false;
+                else
+                        enabled = on_tty();
         }
 
-        return parse_boolean(colors) != 0;
+        return enabled;
 }