<< Back to previous view

[CLJ-1730] Improve `refer` performance Created: 13/May/15  Updated: 08/Oct/18

Status: Open
Project: Clojure
Component/s: None
Affects Version/s: Release 1.6
Fix Version/s: Release 1.11

Type: Enhancement Priority: Major
Reporter: Alex Miller Assignee: Unassigned
Resolution: Unresolved Votes: 3
Labels: ft, performance

Attachments: Text File clj-1730-2.patch     Text File refer-perf.patch     PNG File Screenshot from 2018-08-01 23-23-41.png    
Patch: Code
Approval: Vetted


refer underlies require, use, and refer-clojure use cases and is not particularly efficient at its primary job of copying symbol/var mapping from one namespace to another.

Approach: Some improvements that can be made:

  • Go directly to the namespace mappings and avoid creating filtered intermediate maps (ns-publics)
  • Use transients to build map of references to refer
  • Instead of cas'ing each new reference individually, build map of all changes, then cas
  • For (:require :only ...) case - instead of walking all referred vars and looking for matches, walk only the included vars and look up each one

There are undoubtedly more dramatic changes (like immutable namespaces) in how all this works that could further improve performance but I tried to make the scope small-ish for this change.

While individual refer timings are greatly reduced (~50% reduction for (refer clojure.core), ~90% reduction for :only use), refer is only a small component of broader require load times so the improvements in practice are modest.


expr in a new repl 1.7.0-beta3 1.7.0-beta3+patch
(in-ns 'foo) (clojure.core/refer 'clojure.core) 2.65 ms 0.994 ms
(in-ns 'bar) (clojure.core/refer 'clojure.core :only '[inc dec]) 1.04 ms 0.113 ms
(use 'criterium.core) 0.877 ms 0.762 ms
(require '[clojure.core.async :refer (>!! <!! chan close!)]) 3408 ms 3302 ms

Patch: clj-1730-2.patch

Screening Notes

Patch appears correct but we should consider:

  • non-idiomatic use of if instead of when makes branches hard to read
  • non-idiomatic indentation of if (both branches on one line) hard to read
  • I don't think not found should be an IllegalAccessError, but the original code did this already, so ...
  • the optimistic concurrency loop around the swap will never give up, is this ok?

Comment by Alex Miller [ 07/Sep/17 10:52 AM ]

Patch updated to address first screening comment. I didn't actually find any case of the second one? Give me a pointer.

Comment by Ghadi Shayban [ 01/Aug/18 10:30 PM ]

I suspect that this will not matter much for peak performance. Given the attached picture of clojure.instant loading, this patch may shave a bit off startup time.

(picture made with Bytestacks, profile recorded a JDK11 debug build from today)

Generated at Sun May 19 07:42:53 CDT 2019 using JIRA 4.4#649-r158309.