Definition
An early-exit predicate is a yes-or-no test, one of several evaluated in a fixed order, whose result can settle the final decision so that the remaining tests are skipped, as when a gate rejects a request at its first failed test. The expected decision cost is the average cost of reaching a decision over a stated mix of inputs: the sum of each test’s cost times the probability that evaluation reaches that test. It depends on the test order and the input mix, not only on the code.
The idea
A gate accepts a request only if every one of several tests passes. A request that fails the first test pays for one test; a request that passes them all pays for every test. Valid requests from a well-behaved client therefore pay the full price, while a flood of malformed requests, rejected at the first test, pays almost nothing. A measured mean cost describes the code together with its input mix, never the code alone.
The order of the tests decides which requests pay for which tests. A cheap test that rarely rejects saves little when it runs first, because nearly every request still goes on to the expensive tests. A doorman is a fair picture: if nine in ten people are not on the guest list, checking the list first beats checking shoes first, even though shoes are quicker to inspect. The picture stops where some tests are safe to run only after another test has passed, so not every order is allowed.
Programmers call the short route that most executions take the fast path, and the longer, rarer route the slow path. A feature that can be switched off is the extreme case of an early exit. While the feature is off, every call should leave at the first test, which reads one boolean value, a variable that is either true or false. The disabled feature then costs one memory read and one conditional branch, the instruction that picks which code runs next, per call. Any work placed before that test, such as copying arguments, taking a lock or reading a timer, is paid on every call even while the feature is off, so that work belongs after the test.
How it works
Many programming languages build early exit into their logical operators, which is called short-circuit evaluation. In C, the expression a && b evaluates b only if a is true, and a || b evaluates b only if a is false.
To compute the expected cost of a chain of tests:
List the tests in the order they run, with the cost of test , measured in time or in instructions.
For each test, find its reach probability: the probability, over the input mix of interest, that every earlier test passed, so that this test runs. The first test is always reached.
Multiply each cost by its reach probability and add the products.
To choose between the two orders of two tests and , let and be their rejection probabilities, the fractions of inputs each one rejects. Running first costs on average, because only the fraction that passes goes on to . Running first costs . When both rejection probabilities are above zero, running first is cheaper exactly when . The ratio is a test’s cost per unit of rejection: run the test with the smaller ratio first. The cheapest test belongs first only when it also has the smallest ratio.
Tests may be reordered only if every order gives the same decision and the same effects.
No test may read data whose validity another test establishes: a test that reads a field must follow the length check that proves the field is present.
No test may have a side effect, such as updating a counter, using up a rate limiter’s §9.38 allowance or writing a log entry.
The security policy must not fix the order, as it does when it requires the sender’s authenticity to be verified before the content of a request is acted on.
Worked example
The numbers are invented and measured in s (microseconds). A gate runs test 1, which costs 2 s, and then test 2, which costs 8 s. In the input mix of interest, one quarter of the requests pass test 1 and reach test 2. The expected cost is s. The two groups of requests give the same number: three quarters pay 2 s, one quarter pay s, and s. No single request costs 4 s; the mean is a weighted average of 2 and 10.
Reordering. Test A costs 1 s and rejects 1% of requests. Test B costs 4 s and rejects 90%. Both are pure, meaning they have no side effects and neither depends on the other, so either order is allowed.
A first: s.
B first: s.
The ratio rule agrees: and , so B goes first, although A is four times cheaper. A request that passes both tests costs s in either order: reordering changes the mean, not the worst case. If a flood of malformed requests makes A reject 50% and B reject 10%, A first costs s and B first costs s: the better order flips with the mix.
A disabled feature. A hook, a point in a program where optional code can be attached, runs 2,000 times per second. Version 1 of the hook copies its arguments, which takes 1.2 s, and then tests an on/off flag, which takes 0.05 s. With the feature off, version 1 spends s, that is 2.5 milliseconds, in every second: 0.25% of the processor’s time. Version 2 tests the flag first and, with the feature off, spends s per second, 0.01%. Version 2 is times cheaper while the feature is off, and costs the same as version 1 while the feature is on.
Stated precisely
Let tests run in this order, each with a fixed cost , and let evaluation stop at the first test that rejects. Let be the event that tests to all pass, so that runs; always happens. Write for the probability of over a stated input mix, and for the cost of one decision. The expected decision cost is The worst-case cost, paid by every input that reaches the last test, is in every order.
For two tests with rejection probabilities and over the same mix, the order is cheaper than exactly when . This needs no assumption about how the two results are related, because each order’s cost involves only the probability that its first test passes. For tests whose results are statistically independent, meaning that one test’s result does not change the probability of another’s, sorting by increasing minimizes the expected cost, and a test that never rejects goes last. The proof is an exchange argument: swapping two adjacent tests changes only their own two terms, both multiplied by the same probability of reaching the pair, so the two-test rule decides each adjacent pair. When results are dependent, the reach probabilities must be built from conditional probabilities §15.43, such as the probability that a test rejects given that all earlier tests passed, and each candidate order’s cost must be computed directly.
These statements rest on four named assumptions: pure tests, which have no side effects and give the same decision in every order; fixed costs, the same for every input; a stated mix, on which the probabilities are measured; and, for the sorting rule with more than two tests, independence.
Limits and common mistakes
A mean cost is not a bound. A deadline needs the worst-case execution time §9.33, the longest time any input can take, and reordering pure tests leaves that unchanged.
An attacker chooses the input mix. Inputs crafted to pass every cheap test and fail only the last one pay for the whole chain each time, which turns an expensive last test into a tool for denial of service §1.28, an attack that exhausts a system’s capacity. Place cheap tests that reject hostile inputs early, and limit how often the expensive test can run.
Early exit leaks through time. How long a check takes reveals which test stopped it, a side channel §1.29: an unintended way for information to escape. A test that compares secret data, such as a key or an authentication §1.6 tag, must take the same time for every input, which is called a constant-time implementation §5.36, and the expected-cost argument does not apply to it.
A test’s own cost can depend on the input, as when a comparison of two strings stops at their first difference; the expected cost must then use that test’s mean cost over the mix.
The flag test is the floor, not zero: a disabled feature still costs a read and a branch on every call. The static keys of the Linux kernel lower that floor by rewriting the code while it runs, so that a disabled feature costs a single instruction that does nothing.
Questions answered
Should the cheapest check always run first?
No, the cheapest check should not always run first. Among checks that may legally run in any order, the check with the smallest ratio of cost to rejection probability, the fraction of inputs it rejects, should run first; for more than two checks this rule assumes that the checks’ results are independent. The cheapest check belongs first only when it also has the smallest ratio. In an invented example, check A costs 1 microsecond and rejects 1% of requests, and check B costs 4 microseconds and rejects 90%. A first costs microseconds on average, and B first costs microseconds, so B should run first although A is cheaper.
Three conditions come before any reordering. The checks must be free to reorder: no check may read data that another check validates, no check may have a side effect, and the security policy must not fix the order. The rejection probabilities must come from the input mix that matters, because a different mix can reverse the best order. And reordering lowers only the average: an input that reaches the last check pays for every check in any order, and a check on secret data must take the same time for every input, so that its timing reveals nothing.
Related entries: Conditional probability (§15.43), Sample mean (§11.12), Constant-time cryptographic implementation (§5.36), Worst-case versus average-case complexity (§14.3), Worst-case execution time (WCET) (§9.33), Denial of service (DoS) (§1.28), Side channel (§1.29).