Skip to content

perf(mdo): LRU-мемоизация findCommonModule#619

Closed
nixel2007 wants to merge 1 commit into
developfrom
claude/new-session-wua1z1
Closed

perf(mdo): LRU-мемоизация findCommonModule#619
nixel2007 wants to merge 1 commit into
developfrom
claude/new-session-wua1z1

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 21, 2026

Copy link
Copy Markdown
Member

CF.findCommonModule(name) — тонкая обёртка над
getCommonModulesByName().get(name). Карта мемоизируется, но её тип —
CaseInsensitiveMap, у которой каждый get() сворачивает регистр
ключа-запроса посимвольно (Character.toLowerCase + аллокация строки).

В потребителях (заполнитель индекса ссылок bsl-language-server)
findCommonModule вызывается на каждый идентификатор исходного кода —
десятки тысяч раз на ребилд документа, в основном промахи.

Добавлен LookupCachingMap — декоратор read-only карты поверх
commons-collections4 (новых зависимостей нет), мемоизирующий результаты
get() (включая отрицательные через маркер MISS) в ограниченном по
размеру потокобезопасном LRU. computeCommonModulesByName оборачивает
карту общих модулей; размер кэша max(2048, 2×count) гарантирует, что
положительные попадания не вытесняются.

Co-Authored-By: Claude Opus 4.8 (1M context) noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_01Lsui6HwTYazwFSPSB6Wt5k

Summary by CodeRabbit

  • Performance
    • Enhanced lookup performance for common module discovery through the implementation of efficient caching with automatic memory management, reducing computational overhead during frequent access operations.

CF.findCommonModule(name) — тонкая обёртка над
getCommonModulesByName().get(name). Карта мемоизируется, но её тип —
CaseInsensitiveMap, у которой каждый get() сворачивает регистр
ключа-запроса посимвольно (Character.toLowerCase + аллокация строки).

В потребителях (заполнитель индекса ссылок bsl-language-server)
findCommonModule вызывается на каждый идентификатор исходного кода —
десятки тысяч раз на ребилд документа, в основном промахи.

Добавлен LookupCachingMap — декоратор read-only карты поверх
commons-collections4 (новых зависимостей нет), мемоизирующий результаты
get() (включая отрицательные через маркер MISS) в ограниченном по
размеру потокобезопасном LRU. computeCommonModulesByName оборачивает
карту общих модулей; размер кэша max(2048, 2×count) гарантирует, что
положительные попадания не вытесняются.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lsui6HwTYazwFSPSB6Wt5k
@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 98058296-e194-4dc1-a2c5-a139f126be29

📥 Commits

Reviewing files that changed from the base of the PR and between 4541a7b and 8decfc5.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/mdo/utils/LazyLoader.java
  • src/main/java/com/github/_1c_syntax/bsl/mdo/utils/LookupCachingMap.java

📝 Walkthrough

Walkthrough

A new LookupCachingMap<V> class is added as a read-only Map decorator that wraps a synchronized LRU cache over a backing map. It caches both positive hits and negative misses via a sentinel value. LazyLoader.computeCommonModulesByName is updated to return the map wrapped in LookupCachingMap, with cache size computed by a new lookupCacheSize helper as max(2048, moduleCount * 2).

Changes

LRU Lookup Cache for Common Modules

Layer / File(s) Summary
LookupCachingMap: LRU decorator with negative-result caching
src/main/java/com/github/_1c_syntax/bsl/mdo/utils/LookupCachingMap.java
New public final class LookupCachingMap<V> extends AbstractMapDecorator<String, V>. Constructor takes a backing map and maxCacheSize, initializing a Collections.synchronizedMap-wrapped LRUMap. get(Object key) checks the cache first, using a private MISS sentinel to distinguish cached negatives from uncached entries, then delegates to the decorated map and stores the result.
LazyLoader: wire LookupCachingMap into common-modules lookup
src/main/java/com/github/_1c_syntax/bsl/mdo/utils/LazyLoader.java
computeCommonModulesByName wraps the unmodifiable result map in LookupCachingMap before returning. New lookupCacheSize(int moduleCount) helper computes capacity as Math.max(2048, moduleCount * 2).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hop, hop, the cache is set,
No case-fold done twice — don't fret!
A MISS or a hit, the LRU knows,
The modules are found wherever the rabbit goes.
Bounded by 2048 or twice the count,
Every lookup now flies over the mount! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding LRU memoization to optimize the findCommonModule method, which is the primary objective of this performance-focused PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/new-session-wua1z1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

cf.getCommonModules().forEach(commonModule -> result.put(commonModule.getName(), commonModule));
return Collections.unmodifiableMap(result);
// CaseInsensitiveMap.get сворачивает регистр запроса на каждый вызов, а findCommonModule
// дёргается десятки тысяч раз (на каждый идентификатор при разрешении ссылок). Оборачиваем в

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это внешнее знание

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
72.2% Coverage on New Code (required ≥ 80%)
B Reliability Rating on New Code (required ≥ A)
B Maintainability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@github-actions

github-actions Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Test Results

  402 files  ±0    402 suites  ±0   5m 44s ⏱️ +32s
  286 tests ±0    286 ✅ ±0  0 💤 ±0  0 ❌ ±0 
1 776 runs  ±0  1 776 ✅ ±0  0 💤 ±0  0 ❌ ±0 

Results for commit 8decfc5. ± Comparison against base commit 4541a7b.

♻️ This comment has been updated with latest results.

@nixel2007 nixel2007 marked this pull request as draft June 22, 2026 13:01
@nixel2007 nixel2007 closed this Jun 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants