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:

    The demagogue is usually sly, a detractor of others, a professor of humility and disinterestedness, a great stickler for equality as respects all above him, a man who acts in corners, and avoids open and manly expositions of his course, calls blackguards gentlemen, and gentlemen folks, appeals to passions and prejudices rather than to reason, and is in all respects, a man of intrigue and deception, of sly cunning and management.
    James Fenimore Cooper (1789–1851)