Comment #4 on issue 3533 by siguctua: add Dictionary>>at:ifAbsentValue:
http://code.google.com/p/pharo/issues/detail?id=3533

Of course, you can always use:

dict at: x ifAbsent: y

except that it is not always desirable to send #value message to 'y' argument, especially if you can't tell anything about nature of objects you are storing in dictionary, and when speed is essential, it would be good to have something like this:

at: key ifAbsentValue: defaultValue
        "Answer the value associated with the key or, if key isn't found,
        answer the default value"
        
        ^((array at: (self findElementOrNil: key)) ifNil: [ ^ defaultValue ]) 
value


Cog VM shows a significant difference in delivering an answer:

| dict |
dict := Dictionary new.
dict at: #a put: 1.

[ 1000000 timesRepeat: [ dict at: #foo ifAbsentValue: #bar ] ] timeToRun
 236 234 239

[ 1000000 timesRepeat: [ dict at: #a ifAbsentValue: #bar ] ] timeToRun
 241 234 236 237

[ 1000000 timesRepeat: [ dict at: #foo ifAbsent: [#bar] ] ] timeToRun
 322 318

[ 1000000 timesRepeat: [ dict at: #a ifAbsent: [ #bar ] ] ] timeToRun
 363 336  340




Reply via email to