Subject: bug#66117: 30.0.50; `find-buffer-visiting' is slow when opening large number of buffers

From: Ihor Radchenko <[email-masked]>
Date: Thu, 05 Oct 2023 11:27:55 +0000

Dmitry Gutov <[email-masked]> writes:

> I retested, and it seems most people here won't be impressed by my 
> example. Anyway:
>
> 1. Call (benchmark-run 1 (project-find-regexp "emacs") in an Emacs repo 
> checkout.
> 2. Change xref--collect-matches to call get-file-buffer instead of 
> xref--find-file-buffer (which does some caching). 'M-x 
> byte-compile-file', (load "xref.elc"), and run the benchmark again.
>
> What I get here, is 3.60s vs 5.03.
>
> It's a 1.40s difference over ~95000 calls, though (this is how many 
> matches are produced). Which is meaningful for my case, but probably not 
> for yours.

I can reproduce:

;; original code
(benchmark-run 10 (project-find-regexp "emacs")) ; => (26.459992888000002 17 7.026558985999998)
;; changed `xref--find-file-buffer' to `get-file-buffer'
(benchmark-run 10 (project-find-regexp "emacs")) ; => (43.623003254000004 18 8.161839762000001)

Looking into `xref--find-file-buffer', all it does is memoizing the
previous call. I think that we can easily achieve the same performance
improvement by maintaining approximate cache for Fget_file_buffer -
something like
(if (and (gethash file cache)
           (equal (buffer-local-value 'buffer-file-name (gethash ...)) file))
  <return cached>
 <compute and cache the result>)

Or maybe even cache the last call separately to not pay `gethash' call price.

100% reliable cache is not necessary in this scenario. And not necessary
in my scenario, as I have found via my benchmarks in another message.

-- 
Ihor Radchenko // yantar92,
Org mode contributor,
Learn more about Org mode at <https://orgmode.org/>.
Support Org development at <https://liberapay.com/org-mode>,
or support my work at <https://liberapay.com/yantar92>