Friday, December 05, 2008

On 'inline' in C++

Another question asked, 'what and when to use inline?'

Again, IMHO, inline in C++ was supposed to replace macro function in C. Basically inline support 'macro'ing function with syntactical check on formal parameter. So it is better than creating macro (#define).

Any occurrence of inlined function call, will be replaced automatically with the whole body of the inlined function. This is done automatically during compilation. The advantage - improve speed. Disadvantage - size increased.

The advantage of inline is for runtime optimization. Since during coding or writing code, there's no difference of inlined and normal function, other than the word 'inline'.

When to use?
When our program prioritize runtime performance, use inline. But the disadvantage, it might increase your program's size. But if the only thing matters is runtime storage, don't use inline, since our program tend to be in minimal size without inline.

Rule-of-thumb (ask Mr Stroustrup):
no matter what, if the function body exceeds than 5 (major) lines, never use inline. Use normal function call instead. Since the performance of executing instructions within that size might be comparable to using normal function call (in fact might be slower). So why bother to increase program size without gaining any advantage in performance (or worse, make them slow)?

use it wisely.

-EOF

No comments:

Post a Comment