r/programming • • Sep 02 '26

CTTI is Exponential, RTTI is Linear

https://www.gingerbill.org/article/2026/09/02/ctti-is-exponential-rtti-is-linear/
94 Upvotes

90 comments sorted by

View all comments

Show parent comment

1

u/mr_birkenblatt Sep 03 '26

Worst case is always number of call sites which is linear wrt code size

1

u/gingerbill Sep 03 '26 edited Sep 03 '26

So parametric polymorphism which creates MORE code than just the call sites, isn't a thing?

By definition it is not linear with the code size.

Even using my basic example there of N=4 and K=5, means a maximum possible of 1365 instantiations of the monomorphized code. So even if there are a million calls that cover all of those permutations, there will only be 1365 instantiations of the parametric polymorphic ("parapoly") procedure.

So for each unique permutation, you do get a unique monomorphization. That's not "linear" necessarily, especially if those are determined at compile time through parapoly. You do get more code being generated.

I am not sure why so many people are not understanding this, because this literally happens in many C++ codebases, and it is not hypothetical.

2

u/mr_birkenblatt Sep 03 '26

how many call sites does the function with parametric polymorphism have? this is linear. give me a counter example if you still think otherwise

8

u/gingerbill Sep 03 '26

Do I really have to give the simple example of compile-time execution in C++ templates? Fine:

template <typename A, typename B> struct P {};

template <unsigned N, typename T>
void f(T x) {
    if constexpr (N > 0) {
        f<N - 1>(P<T, int>{});
        f<N - 1>(P<T, char>{});
    }
}

int main() { f<10>(0); }

Three call sites in the source. GCC emits 2047 instantiations of f, i.e. 2^(N+1) - 1. Every instantiation builds new type arguments for its callees, so nothing deduplicates. Now imagine f is a recursive printing procedure, which is a pretty common way of doing it in practice.

The number of call sites is a property of the monomorphized output, not the source, because monomorphization duplicates call sites. A call to g<T> written once inside f<T> becomes one call site per instantiation of f. You're measuring the thing we're arguing about.

Zig's std library is a real example of the naïve printing I describe. The idiom .print("...", .{...}) passes an [anonymous] struct, as it does not have any form of variadic parameters, so every distinct ordering of argument types needs its own instantiation. The implementation is here: https://codeberg.org/ziglang/zig/src/branch/master/lib/std/Io/Writer.zig#L697

It assumes a small number of arguments, and it recurses through the argument types, so it hits exactly the combinatorial explosion I'm describing.