Matt’s First Rule of Performance
All of us know a little bit about code for us to be on the RevNet Development Team, but sometimes it takes more than knowing what to do to accomplish something—like reading an XML file and sending an email from the information inside it, or inserting user input into a database—to do it “right.” I came across a concept from NU’s own Matt Curland the other day that looked something like this:
// Matt’s first rule of performance:
// 0 > 1 > 2
So what does that mean? The gist is that if you need to get a result from a property or method, and you need to manipulate that value in more than one place, it’s better to call it once than call it twice. But even so, it’s better not to call anything at all if you can help it.
An example of this in practice was what he was referring to at the time: (beware, ORM jargon approaching!) the Multiplicity property of a Role object. This RoleMultiplicity is a measure of how many times a unique value could go into a fact table representing the role’s opposite role on a binary fact type i.e. if I had the fact type “Person(ID) has PersonName()” with a uniqueness and mandatory role constraint on the side of the Person object, calling the Multiplicity property of the PersonName’s role would give me RoleMultiplicity.ExactlyOne (opposite role’s constraints signify this).
Little did I know that calling this property was an immensely expensive procedure. It has to get the fact type from the model by using VS2005’s “Store” (as its name implies, stores everything that would be on the diagram, and we have know idea how that’s done; could be something of O(n2) complexity; see how Algorithms comes into play?!), and then create a new collection based on the roles from the model. It thens checks the count of the collection which does a lot of other checks (F11 makes you sick), and then does another loop to check for what multiplicity that role actually has. Before investigating all of that for ourselves, this is what our code looked like:
Before the Rule - Notice the properties referenced multiple times.
After the Rule - Notice how things are pulled out.
So remember:
When in doubt, pull it out.
Syndication
May 24th, 2006 at 10:51 pm
Great post Dave. I think Matt would be proud of your very cleanly stated explaination of his precious rule. Your coding skills and insights are a credit to the group.