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 realize that we are laggards from the past century, still living in what Marx kindly calls ‘the idiocy of rural life,’ and we know that our rural life is like that of the past, not like that of much of the present.
    —For the State of Vermont, U.S. public relief program (1935-1943)