On May 30, 2007, at 23:36 , goran@krampe.se wrote:
Hi!
nicolas cellier ncellier@ifrance.com wrote:
Just tried this very simple one: (I guess the smaller the merrier)
floorLog10bert "from Bert Freundenberg's idea"
(My name occurrencesOf: $n) = 1 ;-)
(self negative or: [self isZero]) ifTrue: [^self error: 'Can''t take log of number <= 0'].
I'd use "self < 1" for the first test to avoid unnecessary message sends (and it's prettier, too).
self < 10 ifTrue: [^0]. self < 100 ifTrue: [^1]. self < 1000 ifTrue: [^2]. self < 10000 ifTrue: [^3]. self < 100000 ifTrue: [^4]. self < 1000000 ifTrue: [^5]. self < 10000000 ifTrue: [^6]. self < 100000000 ifTrue: [^7]. self < 1000000000 ifTrue: [^8]. ^9 "Based on the fact that (SmallInteger maxVal log: 10) floor = 9"
Comparing universal Integer version provided in previous mail and Bert's gives a factor 5 at least
I also noted this and I also used the above approach - though with a binary search. My code is in the mantis issue I posted in the beginning. :)
Anyway, since smaller numbers are likely to be much more common I would guess the ordering above is actually "smarter". And yes, it was fun to see that Strongtalk does the above and its SmallInteger>>printString is very similar to the one I ended up writing in the mantis issue.
I still wonder how common #printString calls are in performance- sensitive code ... I usually use printOn: if performance matters, so maybe that should be optimized, too?
- Bert -