Skip to lesson

Method inlining

Clean code uses many tiny methods such as getPrice(), and every call costs a little time. Millions of calls should add up, yet Java stays fast. What does the JIT do about it?

Inlining copies a small method's body into its caller

Inlining is when the JIT compiler copies a small method's body into the place that calls it, removing the cost of the call.

Inlining means the JIT compiler replaces a method call with the body of the called method. You still write total += s.getMarks();, but the compiled machine code reads the field directly, as if you had written total += s.marks;.

Java
int getMarks() {    return marks;}
// What you write in the hot loop:total += s.getMarks();
// What the compiled code effectively does after inlining:total += s.marks;

The JIT does this inside the compiled code only. Your source and your bytecode do not change, and the program behaves exactly the same. Java's access rules apply to source and bytecode, not to machine code, so inlining a getter of a private field is perfectly safe.

Example 1 · A getter in a hot loop

MarksInlineDemo.javaJava
class Student {    private final int marks;
    Student(int marks) {        this.marks = marks;    }
    int getMarks() {        return marks;    }}
public class MarksInlineDemo {    static long classTotal(Student[] students) {        long total = 0;        for (Student s : students) {            total += s.getMarks();        }        return total;    }
    public static void main(String[] args) {        Student[] students = new Student[60];        for (int i = 0; i < students.length; i++) {            students[i] = new Student(40 + i % 60);        }        long grand = 0;        for (int exam = 0; exam < 20_000; exam++) {            grand += classTotal(students);        }        System.out.println("Grand total: " + grand);    }}
Output
Grand total: 83400000

What this code does

  • classTotal calls getMarks() 60 times per exam and runs for 20,000 exams: 1,200,000 calls. 60 students with marks 40 to 99 add up to 4,170 per exam.
  • In the source every mark goes through the getter. The next example shows what the JIT did with those calls.

Example 2 · PrintInlining shows the getter disappear

Terminal
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintCompilation -XX:+PrintInlining MarksInlineDemo
Sample output
97   67       1       Student::getMarks (5 bytes)
98   68       3       MarksInlineDemo::classTotal (41 bytes)
                              @ 27   Student::getMarks (5 bytes)   inline
98   69 %     4       MarksInlineDemo::classTotal @ 11 (41 bytes)
                              @ 27   Student::getMarks (5 bytes)   accessor
102   70       4       MarksInlineDemo::classTotal (41 bytes)
...
                              @ 27   Student::getMarks (5 bytes)   accessor

What this code does

  • @ 27 is the bytecode position of the getMarks() call inside classTotal. Under the level 3 (C1) compile it says inline; under the level 4 (C2) compiles it says accessor, C2's word for a trivial getter it inlined.
  • getMarks itself was compiled at level 1, the C1 level for trivial methods. The output is trimmed: the real run printed many JDK methods too, and the order of lines can shift slightly between runs.

You can watch it happen with two diagnostic options: -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining. They print, under each compiled method, the calls it contains and whether each one was inlined.

-XX:+UnlockDiagnosticVMOptions must come before -XX:+PrintInlining on the command line. Both are for learning and troubleshooting, not for normal runs.

Why small getters and helper methods cost nothing after JIT

A method call has a cost: the caller saves its state, jumps to the method, sets up a new frame and jumps back. For a getter that does one field read, the call itself is more work than the method body.

Example 3 · Field read versus getter, timed

GetterCostDemo.javaJava
class Order {    int amount;                       // public-style field, read directly
    private final int amountPrivate;  // the same value behind a getter
    Order(int amount) {        this.amount = amount;        this.amountPrivate = amount;    }
    int getAmount() {        return amountPrivate;    }}
public class GetterCostDemo {    static long sumDirect(Order[] orders) {        long sum = 0;        for (Order o : orders) sum += o.amount;        return sum;    }
    static long sumGetter(Order[] orders) {        long sum = 0;        for (Order o : orders) sum += o.getAmount();        return sum;    }
    public static void main(String[] args) {        Order[] orders = new Order[10_000];        for (int i = 0; i < orders.length; i++) {            orders[i] = new Order(100 + i % 900);        }        long check = 0;        for (int round = 1; round <= 6; round++) {            long t0 = System.nanoTime();            for (int k = 0; k < 2_000; k++) check += sumDirect(orders);            long t1 = System.nanoTime();            for (int k = 0; k < 2_000; k++) check += sumGetter(orders);            long t2 = System.nanoTime();            System.out.println("Round " + round + ": field " + (t1 - t0) / 1_000_000                    + " ms, getter " + (t2 - t1) / 1_000_000 + " ms");        }        System.out.println("Check: " + check);    }}
Sample output
Round 1: field 20 ms, getter 21 ms
Round 2: field 10 ms, getter 10 ms
Round 3: field 15 ms, getter 14 ms
Round 4: field 11 ms, getter 16 ms
Round 5: field 11 ms, getter 10 ms
Round 6: field 12 ms, getter 12 ms
Check: 130920000000

What this code does

  • After round 1, the field version and the getter version take the same time within noise (10 to 16 ms per round on this machine). The JIT inlined getAmount(), so both loops compiled to the same machine code.
  • With java -Xint GetterCostDemo (no JIT) the same machine took 960 to 1,355 ms per getter round against 538 to 717 ms for the field: without inlining, the call does cost something. Your numbers will differ.

Inlining removes that cost, and it also opens the door to further optimisations. Once the body sits inside the caller's loop, the JIT can keep values in CPU registers, move work out of the loop and drop checks it has already done. C2 inlines a method by size and hotness. On HotSpot 17 and 21 (x86-64 defaults), a method of up to 35 bytes of bytecode can be inlined anywhere (MaxInlineSize), and up to 325 bytes at a hot call site (FreqInlineSize). Inlining goes up to 15 calls deep (MaxInlineLevel, raised from 9 in Java 14). These are simplified rules; C2 also checks how big the caller has already grown.

Call sites with one, two or many receiver types

A call site is one place in the code where a method is called, such as p.fee(1000) inside a loop. For a call on an interface or a class with subclasses, the receiver type is the actual class of p at run time.

Example 4 · One, two and four payment types at a call site

CallSiteDemo.javaJava
interface Payment {    int fee(int amount);}
class Upi implements Payment {    public int fee(int amount) { return 0; }}
class Card implements Payment {    public int fee(int amount) { return amount / 50; }}
class NetBanking implements Payment {    public int fee(int amount) { return 10; }}
class Wallet implements Payment {    public int fee(int amount) { return amount / 100; }}
public class CallSiteDemo {    // Each method below has its own call site p.fee(...)    static long oneType(Payment[] ps) {        long t = 0;        for (Payment p : ps) t += p.fee(1000);        return t;    }
    static long twoTypes(Payment[] ps) {        long t = 0;        for (Payment p : ps) t += p.fee(1000);        return t;    }
    static long manyTypes(Payment[] ps) {        long t = 0;        for (Payment p : ps) t += p.fee(1000);        return t;    }
    public static void main(String[] args) {        Payment[] one = new Payment[100];        Payment[] two = new Payment[100];        Payment[] many = new Payment[100];        for (int i = 0; i < 100; i++) {            one[i] = new Upi();            two[i] = (i % 2 == 0) ? new Upi() : new Card();            switch (i % 4) {                case 0 -> many[i] = new Upi();                case 1 -> many[i] = new Card();                case 2 -> many[i] = new NetBanking();                default -> many[i] = new Wallet();            }        }        long a = 0, b = 0, c = 0;        for (int round = 0; round < 20_000; round++) {            a += oneType(one);            b += twoTypes(two);            c += manyTypes(many);        }        System.out.println("Fees: " + a + ", " + b + ", " + c);    }}
Output
Fees: 0, 20000000, 20000000

What this code does

  • The three methods contain the same line, t += p.fee(1000), but each is a separate call site with its own profile: only Upi, Upi and Card, or all four types.
  • UPI has no fee, cards pay 2 percent (Rs 20 on Rs 1,000), net banking Rs 10, wallets 1 percent. The results are the same however the JIT compiles the calls; only the speed can differ.

Example 5 · What C2 did at each call site

Terminal
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintCompilation -XX:+PrintInlining CallSiteDemo
Sample output
111   80 %     4       CallSiteDemo::oneType @ 11 (46 bytes)
                              @ 30   Upi::fee (2 bytes)   inline (hot)
                               \-> TypeProfile (47600/47600 counts) = Upi
115   81 %     4       CallSiteDemo::twoTypes @ 11 (46 bytes)
                              @ 30   Upi::fee (2 bytes)   inline (hot)
                              @ 30   Card::fee (5 bytes)   inline (hot)
                               \-> TypeProfile (79100/158200 counts) = Card
                               \-> TypeProfile (79100/158200 counts) = Upi
...
126   82 %     4       CallSiteDemo::manyTypes @ 11 (46 bytes)
                              @ 30   Payment::fee (0 bytes)   virtual call

What this code does

  • oneType: the profile saw only Upi (47600 of 47600 calls), so Upi::fee is inlined. twoTypes: two types, each about half the calls, so both bodies are inlined.
  • manyTypes: four types, each about 25 percent, so C2 keeps a virtual call to Payment::fee. Trimmed: the real output also shows the normal (non-OSR) compiles with the same decisions.

The profile records which receiver types reached each call site. C2 uses that record, in a simplified picture, like this:

  • Monomorphic (one type seen): inline that type's method behind a quick type check.
  • Bimorphic (two types seen): inline both, with a check that picks the right one.
  • Megamorphic (three or more types): usually a normal virtual call, with no inlining. If one type covers at least 90 percent of the calls, C2 can still inline that one.
  • If a type the JIT never saw turns up later, the type check fails and the JVM falls back safely; the deoptimization lesson covers this.

Write clean code first: the JIT rewards small methods

Small, well-named methods are good for people and good for the JIT. Each one is easy to read and test, and each is small enough to be inlined into its hot callers.

Example 6 · Small named methods in a shop bill

ShopBillDemo.javaJava
import java.util.List;
record Item(String name, int price, int qty) {}
public class ShopBillDemo {    static int lineTotal(Item item) {        return item.price() * item.qty();    }
    static int subtotal(List<Item> items) {        int sum = 0;        for (Item item : items) {            sum += lineTotal(item);        }        return sum;    }
    static int gst(int amount) {        return amount * 5 / 100;               // 5 percent GST on store goods    }
    static int studentDiscount(int amount, boolean hasIdCard) {        return hasIdCard ? amount / 10 : 0;    // 10 percent off with an ID card    }
    static int finalBill(List<Item> items, boolean hasIdCard) {        int sub = subtotal(items);        return sub + gst(sub) - studentDiscount(sub, hasIdCard);    }
    public static void main(String[] args) {        List<Item> order = List.of(                new Item("Notebook", 60, 2),                new Item("Pen", 20, 3),                new Item("Eraser", 15, 4));
        System.out.println("Subtotal: Rs " + subtotal(order));        System.out.println("With ID card: Rs " + finalBill(order, true));        System.out.println("Without ID card: Rs " + finalBill(order, false));
        long total = 0;                        // a busy sale hour: 100,000 bills        for (int i = 0; i < 100_000; i++) {            total += finalBill(order, i % 2 == 0);        }        System.out.println("Peak-hour total: Rs " + total);    }}
Output
Subtotal: Rs 240
With ID card: Rs 228
Without ID card: Rs 252
Peak-hour total: Rs 24000000

What this code does

  • finalBill reads like the rule it implements: subtotal plus GST minus the student discount. Each helper is a few bytes of bytecode, well under the 35-byte limit.
  • During the 100,000-bill loop the JIT can inline the helpers into finalBill, and finalBill into the loop, so the clean version costs nothing extra in hot code.

Merging methods by hand to "save calls" makes code harder to read and almost never makes hot Java code faster. Very large methods are the real problem. C2 will not inline a big method into its callers, and on HotSpot a method with more than 8,000 bytes of bytecode is not JIT-compiled at all by default (DontCompileHugeMethods), so it stays in the interpreter forever. Generated code and giant switch methods sometimes hit this limit.

Megamorphic call sites are rarely worth fixing either. Design with interfaces where the design needs them, then measure. Change a design for speed only when a profiler shows that a specific call site matters.

Next step

Check your understanding

12 quick questions