Info
해당 글에서는 컴파일타임에 타입 추론을 위해서 사용되는 구조체가 런타임에 성능에 관여하는지에 대해서 알아본다.
질문
If a struct is only used for type deduction through
using, is it evaluated solely at compile time and doesn’t incur any runtime cost or memory usage?
ChatGPT의 말:
You’re absolutely right—all of these structs are pure, compile-time “type plumbing”, and under normal use they generate zero runtime code and occupy no memory in your final binary. Here’s why:
이를 기반으로 확인해본 예시는 다음과 같다.
#include "TypeList.hpp"
struct Large { char buf[1024*100]; };
#define CASE_1 // or #define CASE_2
int main() {
#ifdef CASE_1
// purely compile-time, no instantiation
using L = Large;
using TL = khan::TypeList<double, char, L>;
#endif
#ifdef CASE_1
// some trivial runtime work
typename khan::TypeAt_t<TL,2> x{};
#else
Large x{};
#endif
x.buf[0] = 42;
return x.buf[0];
}GPT의 말이 사실이라면 위 둘의 ASM 코드는 정확하게 같아야한다. 메모리 할당과 런타임 실행에 영향이 없어야하기 때문이다.
테스트 결과 ASM은 다음과 같다.
.file "main.c"
.text
.section .text.startup,"x"
.p2align 4
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
.LFB17:
subq $40, %rsp
.seh_stackalloc 40
.seh_endprologue
call __main
movl $42, %eax
addq $40, %rsp
ret
.seh_endproc
.def __main; .scl 2; .type 32; .endef
.ident "GCC: (MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders, r3) 14.2.0"둘 다 위와 같은 코드가 정확히 똑같게 생성되었다.
결론적으로 GPT의 말과 같이 ‘컴파일 타임에 타입 추론(deducate)을 위해서 활용된 구조체는 메모리 및 런타임 리소스에 영향을 전혀 미치지 않는다는 것을 알 수 있다.
단, 컴파일러 최적화를
-O0으로 최소화 시키는 경우, 위와 같은 동작 없이 임시변수를 모두 생성한다.