Question

I've recently seen a Util class written by my friend having so many inline methods. The class is much about images and has methods like

public static inline function resize ( img:Image, width:Int, height:Int)
{
    //... method implementation goes here.
}

I've asked him why the usage of inline. I know that the compiler changes

var img:Image = ImgUtil.resize(img, 100, 100);

to

var img:Image = // Implementation of method here

He simply said that it reduces calls to functions and to only use them on utility methods. Doesn't copying the same code every time increase program size?

Is this needed nowadays? If needed, when should one use them?

EDIT

I'm listing the most problems and advantages in a list given in the link Patrick provided to help future viewers who don't want to go through links.

Problems

Replacing a call site with an expanded function body can worsen performance in several ways :

  • In applications where code size is more important than speed, such as many embedded systems, inlining is usually disadvantageous except for very small functions, such as trivial mutator methods.
  • The increase in code size may cause a small, critical section of code to no longer fit in the cache, causing cache misses and slowdown.
  • The added variables from the inlined procedure may consume additional registers, and in an area where register pressure is already high this may force spilling, which causes additional RAM accesses.
  • A language specification may allow a program to make additional assumptions about arguments to procedures that it can no longer make after the procedure is inlined.
  • If code size is increased too much, resource constraints such as RAM size may be exceeded, leading to programs that either cannot be run or that cause thrashing. Today, this is unlikely to be an issue with desktop or server computers except with very aggressive inlining, but it can still be an issue for embedded systems.

Typically, compiler developers keep these issues in mind, and incorporate heuristics into their compilers that choose which functions to inline so as to improve performance, rather than worsening it, in most cases.

Advantages:

Inline expansion itself is an optimization, since it eliminates overhead from calls, but it is much more important as an enabling transformation. That is, once the compiler expands a function body in the context of its call site—often with arguments that may be fixed constants -- it may be able to do a variety of transformations that were not possible before. For example, a conditional branch may turn out to be always true or always false at this particular call site. This in turn may enable dead code elimination, loop-invariant code motion, or induction variable elimination.

Was it helpful?

Solution

Wikipedia will tell you more than you need about that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top