]> git.ipfire.org Git - thirdparty/coreutils.git/commitdiff
cut: avoid fwrite calls for smaller amounts of data
authorPádraig Brady <P@draigBrady.com>
Mon, 23 Mar 2026 17:42:27 +0000 (17:42 +0000)
committerPádraig Brady <P@draigBrady.com>
Sun, 5 Apr 2026 12:15:56 +0000 (13:15 +0100)
This is quite significant:

yes abcdfeg | head -n1MB > big-file

$ time src/cut-before -b1,3 big-file >/dev/null
real 0m0.050s

$ time src/cut-after -b1,3 big-file >/dev/null
real 0m0.029s

src/cut.c

index 9f73eefd5c31a7a6d5e32d91ea60527005f06155..0dc66c4ec1b508aafb06065e54d4eb1726a9faa3 100644 (file)
--- a/src/cut.c
+++ b/src/cut.c
@@ -405,6 +405,16 @@ skip_whitespace_run (mbbuf_t *mbuf, struct mbfield_parser *parser,
 static void
 write_bytes (char const *buf, size_t n_bytes)
 {
+  /* Avoid a function call for smaller amounts,
+     using instead the macro to directly interact with the stdio buffer.  */
+  if (n_bytes <= 4)
+    {
+      for (size_t i = 0; i < n_bytes; i++)
+        if (putchar (buf[i]) < 0)
+          write_error ();
+      return;
+    }
+
   if (fwrite (buf, sizeof (char), n_bytes, stdout) != n_bytes)
     write_error ();
 }