13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Caching Temporary VariableA Performance Measurement has shown you that an expression in a method is a bottleneck.How do you improve the performance of a method?Many performance related decisions sacrifice programming style to the needs of demanding userswith limited machine resources. Successful performance tuning hinges on being explicitly awareof this tradeoff and only introducing changes that pay back in increased performance more thanthey cost in increased maintenance.As with variables, the scope and extent of a performance tuning decision dramatically affect itscost. Performance related changes that are confined to a single object are good, changes that onlyaffect a single method are even better.All performance tuning boils down to two techniques- either you execute code less often or youexecute code that costs less. Of these, the first is often the most valuable. It relies on the fact thatfor reasons of readability, expressions are often executed several times even though they return thesame value. Caching saves the value of the expression so that the next time the value is usedinstantly.The biggest problem with caches is their assumption that the expression returns the same value.What if this isn't true? What if it is true for a while, but then the value of the expression changes?You can limit the complexity introduced by the need to keep a cache valid by limiting the scopeand extent of the variable used for the cache.Set a temporary variable to the value of the expression as soon as it is valid. Use the variableinstead of the expression in the remainder of the method.For example, you might have some graphics code that uses the bounds of the receiver. Ifcalculating the bounds is expensive, you can transform:self children do: [:each | ...self bounds...]into:| bounds |bounds := self bounds.self children do: [:each | ...bounds...]If the cost of calculating the bounds dominates the cost of the method, this takes a method that islinear in cost in the number of children and turns it into one that is constant.Role Suggesting Temporary Variable Name explains how to name the variable. Caching InstanceVariable caches expression values if they are used from many methods.<strong>Coding</strong> <strong>Patterns</strong> page 80 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!