cmp: stop skipping bytes if EOF is reached

Currently, if a skip value is larger than the file size, cmp will continue
to loop and call getc() until the skip count is satisfied, even though
EOF has been reached.

For large skip values (e.g., 1 billion), this results in significant
CPU waste and execution time (e.g., 11 seconds on a modern CPU).

This patch checks for EOF inside the skip loop and breaks early.

Test case:
$ touch empty.txt
$ time ./busybox cmp empty.txt empty.txt 1000000000 1000000000

Before:
real    0m10.937s

After:
real    0m0.002s

function                                             old     new   delta
cmp_main                                             594     616     +22

Signed-off-by: Giorgi Tchankvetadze <giorgitchankvetadze1997@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
This commit is contained in:
Giorgi Tchankvetadze authored and Denys Vlasenko committed 2026-01-18 01:41:19 +01:00
1 parent 26e9afe22d
commit 3bfbce8312
1 file changed
+2 -2
+2 -2
View File
@@ -113,8 +113,8 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
fmt = fmt_differ;
if (ENABLE_DESKTOP) {
while (skip1) { getc(fp1); skip1--; }
while (skip2) { getc(fp2); skip2--; }
while (skip1) { if (getc(fp1) == EOF) break; skip1--; }
while (skip2) { if (getc(fp2) == EOF) break; skip2--; }
}
do {
if (max_count >= 0 && --max_count < 0)