This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: Optimistic vs Pessimistic Messaging
Feed Title: Travis Griggs - Blog
Feed URL: http://www.cincomsmalltalk.com/rssBlog/travis-rss.xml
Feed Description: This TAG Line is Extra
Here's an interesting little thing I discovered. Now and then again, you have a case where you need to do some introspective method determination. Basically, you have a "if I could actually send a given message to some receiver, I might do things I little different than I might otherwise."
Smalltalk has all kinds of approachable reflection. An example:
This is what I might call the "pessimistic" mode. We assume the object can't. We check to see if it can, and only when we've ascertained that do we proceed. It certainly clarifies the intent quite well too. Another approach might be this:
[receiver froboniwitz] on: MessageNotUnderstood do: [:ex | ]
This is not as "clear". One can extend block with some method called try or attempt to add a little clarity. This is what I might call an "optimistic" approach. Assume the object can do what we want. Pick up the pieces when we're wrong.
Of interest to me, is how the two approaches perform. If you're using either of these techniques in a code site where it happens quite often, this becomes a legitimate concern. On a G4, the pessimistic case spends all of the time in the check. Or rather, for a simple method, the cost is approximately the same whether you can or can't. The optimisitic approach pays quite a different price based on whether the assumption pays off or the we pick up the pieces. For the case that succeeds, it is ~50 times faster than the pesimistic case. Quite an improvement. But for the failed case, it's about 33% slower.
The conclusion might be that the optimistic solution definitely pays off when you know that your send stands a higher chance of succeeding than otherwise. But if you expect to usually fail, you're better off taking the cost of the check.