Idea for a possibly better Collection occurrencesOf method.
Ramon Leon
ramonleon at cox.net
Tue Sep 12 07:23:34 UTC 2006
>>
>> It is also an extra activation per element of the collection (because
>> the ifTrue:-block in the original version gets inlined) which actually
>> shows in a quick benchmark:
>> "Create a list with 1 million true/false elements"
>> list := Array new: 1000000.
>> 1 to: list size do:[:i| list at: i put: i even].
>> "Search for occurances of true by various means"
>> anObject := true.
>> tally := 0.
>> time1 := [list do:[:each| anObject = each ifTrue:[tally := tally +
>> 1]]] timeToRun.
>> time2 := [list inject: 0 into: [:tally :each |
>> anObject = each
>> ifTrue: [tally := tally + 1]
>> ifFalse: [tally]]] timeToRun.
>> time3 := [list count:[:each| each = anObject]] timeToRun.
>> { time1. time2. time3}
>>
>> This results in #(397 590 600) on my machine with the significant
>> difference that being between ~400ms (original version) vs. ~600ms
>> (with extra activation).
>>
>> Cheers,
>> - Andreas
There's an unnecessary assignment in your inject into test. It should be...
time2 := [list inject: 0 into: [:tally :each |
anObject = each
ifTrue: [tally + 1]
ifFalse: [tally]]] timeToRun.
Not that it makes much difference in the benchmark.
More information about the Squeak-dev
mailing list
|