On Fri, Nov 28, 2008 at 5:09 PM, Chouser <[EMAIL PROTECTED]> wrote: > > On Fri, Nov 28, 2008 at 9:38 AM, Michael Wood <[EMAIL PROTECTED]> wrote: >> >> I imagine counting characters in a string will be quicker than setting >> up a bunch of pointers or copying a bunch of characters and then >> garbage collecting them again. >> >> They might both be O(1), but one O(1) is still likely bigger than the other >> :) > > It's easy enough to measure: > > user=> (def s (apply str (replicate 1000 \x))) > #'user/s > user=> (time (dotimes [_ 1000000] (seq s))) > "Elapsed time: 96.660809 msecs" > nil > user=> (time (dotimes [_ 1000000] (empty? s))) > "Elapsed time: 100.079805 msecs" > nil > user=> (time (dotimes [_ 1000000] (== 0 (count s)))) > "Elapsed time: 67.824077 msecs" > nil > > You can also test with s as an empty string. A string thats 1000 > chars long doesn't appear to be any slower (certainly not 1000 times > slower) than an empty string, for any of the methods. This > demonstrates O(1) for all of them and also suggests that seq is not > doing anything "for each character". This is what you should expect, > since seq is a view it doesn't ever copy whole data structures. > > count does seem to be a bit faster than seq or empty. I'm guessing > this is because it doesn't have to allocate a new object the way seq > may have to. If you're doing a million of these tests, is the 0.01 > seconds it costs to do (seq 0) over (== 0 (count s)) really worth the > extra set of nesting parens, the doubling of character, and the > doubling of the number of symbols? Personally, I would say no. And > if you're doing fewer than a million, it's certainly not worth it.
Fair enough. Premature optimisation and all that. I was just interested :) > So write code for the programmer rather than the computer -- write it > the way that will be the easiest for yourself and future maintainers > to understand. True. -- Michael Wood <[EMAIL PROTECTED]> --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---