Subroutine - Optimization of Subroutine Calls

Optimization of Subroutine Calls

There is a significant runtime overhead in a calling a subroutine, including passing the arguments, branching to the subprogram, and branching back to the caller. The overhead often includes saving and restoring certain processor registers, allocating and reclaiming call frame storage, etc.. In some languages, each subroutine calls also implies automatic testing of the subroutine's return code, or the handling of exceptions that it may raise. In object-oriented languages, a significant source of overhead is the intensively used dynamic dispatch for method calls.

There are some seemingly obvious optimizations of procedure calls that cannot be applied if the procedures may have side effects. For example, in the expression (f(x)-1)/(f(x)+1), the function f must be called twice, because the two calls may return different results. Moreover, the value of x must be fetched again before the second call, since the first call may have changed it. Determining whether a subprogram may have a side effect is very difficult (indeed, undecidable). So, while those optimizations are safe in purely functional programming languages, compilers of typical imperative programming usually have to assume the worst.

Read more about this topic:  Subroutine

Famous quotes containing the word calls:

    We take a fancy to something: and scarcely have we thoroughly taken a fancy to it when that tyrant in us calls out: “Give me that in sacrifice”—and we give it.
    Friedrich Nietzsche (1844–1900)