Variable Usage: Span and Live Time

posted on 2004-11-12 at 23:36:06 by Joel Ross

I've been (slowly) reading Code Complete. Tonight, I started chapter 10: General Issues in Using Variables. In 10.4, Steve talks about two measurements that you want to try to minimize: average span and live time.

Span is the number of lines of code between between references to a variable. The average is a total of all of the spans, divided by the number of variable references minus 1. For example:

int a = 1;
int b = 2;
int c = a + b;

The variable a has a span of 1 - one line between it's initialization and it's next reference. The variable b has a span of 0. There are no lines between the two references. The gist of what the book says is that by keeping the uses of a variable close to each other, it will be easier to figure out what the value for a variable will be.

On the other hand, live time is the time a variable is in play. It is the number of lines from first reference to last reference. In the example, a has a live time of 3, while b has a live time of 2. The argument for a short live time is twofold. First, by declaring and initializing variables close to where they are used, you can ensure that the value of the variable isn't changed in other parts of the program. Second, if you limit the use of a local variable, it will be easier to refactor because you don't have to worry about references to the variable spread throughout the whole method. It's use will be contained.

The book says you should try to minimize both, but my question (and belief) is this. If you keep the average span low, does it really matter if the live time grows? Obviously you don't want to let your methods grow to be huge, but if you are utilizing the variable over and over, does the live time really matter? Or am I off base here?

The next section, which relates to the above is about variable scope. I've never done any testing, but I'm curious about one thing. In C#, if you declare a variable inside a loop, it's scope is local to that loop particular loop only. Is that more or less efficient than declaring a variable outside the loop and initializing it inside the loop?

You see, I need to know these things. I don't want my code ending up on The Daily WTF!

Categories: Development