Inlining and Devirtualization

Sumeet More
2 min readAug 23, 2020

--

I agree learning new technologies like kubernetes,docker etc are really good to expand one’s toolbox but today let’s understand some compiler level optimization because all these fancy new technologies use these optimization somewhere down the line.

For today , Let’s understand what is inlining and devirtualization.

  • Inlining

Wiki definition — In computing, inline expansion, or inlining, is a manual or compiler optimization that replaces a function call site with the body of the called function.

To simplify and understand this, when function/method is called while execution — code inside function and other metadata related to function can be present somewhere else and it is obvious to get that data and execute the function will take some time. However, inlining says that compiler will take entire function with its code and other data on call site and execute. This way time will reduce and program will execute faster.

All good till now ? Let’s move on to Devirtualization.

To exhibit polymorphism, we sometimes use virtual methods in base class & override them in dervied classes. This is dynamic in nature because you never know which method unless runtime understand which object is called. So runtime decides which method to call. so it is runtime who is responsible for this code than compiler. Let’s step back and understand can inlining applied here? Nope. Why? it is driven by runtime and inlining is driven by compiler. Since compiler doesn’t know which method will be called, this makes it tough to know on compile time.

What if I tell you there is a way we might be able to inline these virtual method calls. Let’s understand how — dervied classes can be sealed or applied final keyword (C++) . What this in general means is that you cannot inherit from that class if it is sealed why would you do that? simple — security, not want to extend functionality of that class to something it was not intended to.

Got it. But what this sealed keyword has to do with inlining and all?

Interesting behaviour exhibits when you make class sealed is that compiler doesn’t do more checking on which other classes are inheriting this class or its method. Due to which if class is sealed there is a good possibility that virtual method of that class gets inlined and your program runs faster. YAY!

Happy Learning ☺

--

--

Sumeet More
Sumeet More

Written by Sumeet More

Software Engineer 2 at Microsoft | Backend Engineer and Architect| Blockchain & ML enthusiast | C#,.NET Core, Rust, Javascript and Go

No responses yet