[Pharo-users] The most upvoted stackoverflow question - also holds for Pharo

Kasper Østerbye kasper.osterbye at gmail.com
Wed Sep 11 03:20:00 EDT 2019


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.pharo.org/pipermail/pharo-users_lists.pharo.org/attachments/20190911/b68cc937/attachment.html>


More information about the Pharo-users mailing list