Thursday, July 8, 2010

Understand the Attraction of Small Functions

From http://petesbloggerama.blogspot.com/ -

Bill Wagner, in his excellent book, “Effective C#” Second Edition (which I reviewed here), gives a good example in his “Item 11 – Understand the Attraction of Small Functions”:

Bill says that one of the most common examples of premature optimization is when you create longer, more complicated methods in the hope of avoiding method calls.

The .NET Runtime performs JIT compilation on a method – by – method basis at runtime, as the methods are used. Methods that do not ever get called don’t get JITed. Bill gives a short example:

public string BuildMsg( bool takeFirstPath )
{
StringBuilder msg = new StringBuilder( );
if ( takeFirstPath )
{
msg.Append( "A problem occurred." );
msg.Append( "\nThis is a problem." );
msg.Append( "imagine much more text" );
} else
{
msg.Append( "This path is not so bad." );
msg.Append( "\nIt is only a minor inconvenience." );
msg.Append( "Add more detailed diagnostics here." );
}
return msg.ToString( );
}


The first time BuildMsg gets called, both paths are JITed, but only one is needed. But if you rewrote the method this way:

public string BuildMsg( bool takeFirstPath )
{
if ( takeFirstPath )
{
return FirstPath( );
} else
{
return SecondPath( );
}
}

-- the body of each clause has been factored into its own method, and that method can be JITed on demand rather than the first time BuildMsg is called. The example is deliberately short and contrived, but think about how you code: Do you write code with 20 or more statements in each branch? How about switch statements where the body of each case block is defined inline instead of in separate methods?

Followers

Blog Archive