Idea for a possibly better Collection occurrencesOf method.

Andreas Raab andreas.raab at gmx.de
Tue Sep 12 02:03:12 UTC 2006


tim Rowledge wrote:
> You might possibly be able to measure a small performance cost to using 
> inject:into: because it passes down to a virtually identical loop (ie 
> uses a temp, a do: loop etc) and costs you one extra message send or 
> so.  If someone chose to write the compiler optimiser code to inline 
> inject:into: then it would not cost even that.

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



More information about the Squeak-dev mailing list