[webkit-dev] Better to store a local variable or call a method repeatedly?

Darin Adler darin at apple.com
Wed Jan 6 10:54:34 PST 2010


On Jan 6, 2010, at 10:46 AM, Chris Fleizach wrote:

> I see a lot of code that calls the same function a number of times in the same scope.
> 
> Is it better to store that result in a local variable, or is it better to repeatedly call a method...
> 
> in this example, node() is called two times
> 
>    return !m_renderer->node() || !m_renderer->node()->isContentEditable();
> 
> Would it better to write it as 
> 
> 	Node* node = m_renderer->node();
> 	return !node || !node->isContentEditable();

Some advantages to using a local variable:

    1) If the function is a non-trivial function, this can be faster.

    2) Name of local variable can be helpful for additional documentation.

Some advantages to calling a function twice:

    1) In cases where the function is a trivial inline function, this can be slightly faster. Saves allocating a slot on the stack to store the variable.

    2) No need to name the local variable. Can avoid confusion by not having a name.

    3) Eliminates the danger the local variable could be holding a stale pointer or other stale value.

I lean heavily in the “use a local variable” direction almost all the time, but Maciej has pushed me in the other direction in the past.

    -- Darin



More information about the webkit-dev mailing list