The most upvoted question/answer on stackoverflow is this one:
https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array/11227902#11227902

I wanted to see if the results could be reproduced in Pharo, and indeed
they can (though I only get a factor 2-3 difference). The following method
does the trick:

branchPrediction
| size data rnd sum start |
size := 32768.
data := ByteArray new: size.
rnd := Random new: 0.
1 to: size do: [ :i | data at: i put: (rnd nextInt: 256) - 1 ].
“sorting the array makes the loop faster"
data sort.
sum := 0.
start := DateAndTime current.
10000
timesRepeat: [ 1 to: size do: [ :i |
(data at: i) > 128
ifTrue: [ sum := sum + (data at: i) ] ] ].
^ {(DateAndTime current - start) asMilliSeconds.
sum}

Though it is old news, it is still kind of cool.

Best,

Kasper

Reply via email to