help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to count the number of occurrences of a character in a string?


From: Oleh Krehel
Subject: Re: How to count the number of occurrences of a character in a string?
Date: Wed, 14 Oct 2015 12:04:52 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/25.0.50 (gnu/linux)

Hi Joost,

Joost Kremers <joost.m.kremers@gmail.com> writes:

> You should byte-compile them. Makes the difference between cl-count and
> the rest even bigger.
>  
> These are the results from only one run (each function called 100000
> times), but I get similar results when I repeat the test:
>
> ,----
> | cl-count                            0.697451
> | count-char-in-string-cl-count       0.743856
> | count-char-in-string-mapcar         2.196961
> | count-char-in-string-mapc           1.817378
> | count-char-in-string-cdr            1.669147
> | count-char-in-string-string-match   3.815134
> `----
>
> (I left out split-string as it produces the wrong result when the char
> being counted appears twice in a row.)
>
> The cl-count vs. count-char-in-string-cl-count are a direct call to
> cl-count vs. cl-count wrapped in a function. There is obviously some
> overhead to the additional function call, but even then cl-count wins
> hands down.
>
> Code is here:
>
> https://gist.github.com/joostkremers/0e07a35c85758a2fcb52

Thanks for the test cases. Here are their results on my machine:

cl-count                            0.821659
my-count                            0.378911
count-char-in-string-cl-count       0.853604
count-char-in-string-mapcar         1.367351
count-char-in-string-mapc           1.372528
count-char-in-string-cdr            1.123716
count-char-in-string-string-match   2.478769

And here's the code of my-count - it's just cl-count simplified to work
only on strings:

(defun my-count (char str)
  (let ((count 0)
        (end (length str))
        (i 0)
        x)
    (while (< i end)
      (setq x (aref str i))
      (if (eq char x)
          (setq count (1+ count)))
      (setq i (1+ i)))
    count))

While `my-count' is twice as fast, I'd still recommend to use
`cl-count', unless the code is very performance-critical.

    Oleh



reply via email to

[Prev in Thread] Current Thread [Next in Thread]