TIL: puts() is faster than printf()

April 30, 2026

Create a file with name hello.c and write the following code.

#include <stdio.h>

int main(void) {
    printf("hello, world\n");

    return 0;
}

We can pass option -S to generate assembly code of this hello.c program using GCC.

gcc –S hello.c

The command generates the hello.s file with following code.

	.file	"hello.c"
	.text
	.section	.rodata
.LC0:
	.string	"hello, world"
	.text
	.globl	main
	.type	main, @function
main:
.LFB0:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	leaq	.LC0(%rip), %rax
	movq	%rax, %rdi
	call	puts@PLT
	movl	$0, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE0:
	.size	main, .-main
	.ident	"GCC: (Debian 14.2.0-19) 14.2.0"
	.section	.note.GNU-stack,"",@progbits

The above code is generated using GCC v14.2.0. As of writing, in the above, you won't be able to find printf() function. Instead, as you can see in the highlighted (bold) lines, that it use puts() function and \n is removed from string "hello, world" as puts() function add \n at the end.

This is the part of optimization done by GCC because we are not formatting the string with any expression in printf() function. We are just printing the string. If that is the case, GCC is smart enough to replace the printf() call with puts() and remove \n from the string at the end if present. If you really want to keep printf() function, you need to pass -fno-builtin-printf option.

gcc -S -fno-builtin-printf hello.c

Here is the output.

	.file	"hello.c"
	.text
	.section	.rodata
.LC0:
	.string	"hello, world\n"
	.text
	.globl	main
	.type	main, @function
main:
.LFB0:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	leaq	.LC0(%rip), %rax
	movq	%rax, %rdi
	movl	$0, %eax
	call	printf@PLT
	movl	$0, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE0:
	.size	main, .-main
	.ident	"GCC: (Debian 14.2.0-19) 14.2.0"
	.section	.note.GNU-stack,"",@progbits

Furthermore, the optimization shouldn't happen if we do formatting.

#include <stdio.h>

int main(void) {
    int x = 42;
    printf("hello, world %d\n", x);

    return 0;
}

For you: Generate the assembly code and confirm!

No comments:

Post a Comment