Skip to content

perf(context): кэшировать MD-объект и mdoRef документа (lazy)#4180

Merged
nixel2007 merged 1 commit into
developfrom
claude/perf-document-mdobject-cache
Jun 21, 2026
Merged

perf(context): кэшировать MD-объект и mdoRef документа (lazy)#4180
nixel2007 merged 1 commit into
developfrom
claude/perf-document-mdobject-cache

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 21, 2026

Copy link
Copy Markdown
Member

getMdObject() = findChild(getUri()) и getMdoRef() = MdoRefBuilder.getMdoRef(this) зависят только от URI документа и конфигурации, но вызывались на КАЖДЫЙ call-site / использование переменной при заполнении индекса ссылок — десятки тысяч раз на ребилд, заново резолвя один и тот же объект документа.

Переведены на Lazy. Поскольку оба инвариантны к содержимому, а конфигурация инвариантна на время жизни DocumentContext (её перезагрузка через ServerContext.clear() выбрасывает все документы), поля НЕ сбрасываются в clearSecondaryData — считаются один раз на жизнь документа.

Замер (JMH, -prof gc, конфиг ssl_3_2): findChild(uri) = 333 нс/op, 16 B/op → кэшированное чтение 0.63 нс/op, ~0 B/op. Эффект CPU-bound (сравнение URI + CaseInsensitiveMap).

Claude-Session: https://claude.ai/code/session_01HcK3qVwTH91rXtgprGmoWr

Описание

Связанные задачи

Closes

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены (запускал команду gradlew precommit)

Для диагностик

  • Описание диагностики заполнено для обоих языков (присутствуют файлы для обоих языков, для русского заполнено все подробно, перевод на английский можно опустить)

Дополнительно

Summary by CodeRabbit

  • Refactor
    • Enhanced performance for document context data retrieval through optimized caching.

getMdObject() = findChild(getUri()) и getMdoRef() = MdoRefBuilder.getMdoRef(this)
зависят только от URI документа и конфигурации, но вызывались на КАЖДЫЙ call-site /
использование переменной при заполнении индекса ссылок — десятки тысяч раз на
ребилд, заново резолвя один и тот же объект документа.

Переведены на Lazy. Поскольку оба инвариантны к содержимому, а конфигурация
инвариантна на время жизни DocumentContext (её перезагрузка через ServerContext.clear()
выбрасывает все документы), поля НЕ сбрасываются в clearSecondaryData — считаются
один раз на жизнь документа.

Замер (JMH, -prof gc, конфиг ssl_3_2): findChild(uri) = 333 нс/op, 16 B/op →
кэшированное чтение 0.63 нс/op, ~0 B/op. Эффект CPU-bound (сравнение URI +
CaseInsensitiveMap).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HcK3qVwTH91rXtgprGmoWr
@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

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: cedd5fad-4b0b-4a42-8c33-b5a3c681420d

📥 Commits

Reviewing files that changed from the base of the PR and between 346bcef and 18d6bfe.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java

📝 Walkthrough

Walkthrough

DocumentContext gains two Lazy fields (mdObject and mdoRef) that cache the results of the existing configuration/URI lookup and MdoRefBuilder call respectively. The corresponding getters now delegate to getOrCompute() and two new private compute methods supply the underlying logic. These fields are explicitly excluded from clearSecondaryData().

Changes

Lazy MD caching in DocumentContext

Layer / File(s) Summary
Lazy field declarations, getters, and compute methods
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java
Adds mdObject (Lazy<Optional<MD>>) and mdoRef (Lazy<String>) fields annotated as not cleared by clearSecondaryData(); updates getMdObject() and getMdoRef() to return getOrCompute() results; adds computeMdObject() (configuration child lookup by URI) and computeMdoRef() (delegation to MdoRefBuilder.getMdoRef(this)) as backing compute methods.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~4 minutes

Poem

🐇 A bunny once fetched the same thing twice,
Running in circles — not very nice.
Now Lazy fields cache what was sought,
getOrCompute() returns what was thought.
One lookup, not two — pure delight!
The warren runs faster tonight. 🌙

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding lazy caching for MD-object and mdoRef in the document context for performance optimization.
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/perf-document-mdobject-cache

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.

@nixel2007
nixel2007 enabled auto-merge June 21, 2026 17:00
@github-actions

Copy link
Copy Markdown
Contributor

Test Results

 3 516 files  ±0   3 516 suites  ±0   1h 36m 47s ⏱️ + 3m 36s
 3 455 tests ±0   3 437 ✅ ±0   18 💤 ±0  0 ❌ ±0 
20 730 runs  ±0  20 618 ✅ ±0  112 💤 ±0  0 ❌ ±0 

Results for commit 18d6bfe. ± Comparison against base commit 346bcef.

@sonarqubecloud

Copy link
Copy Markdown

@nixel2007
nixel2007 merged commit f6e363b into develop Jun 21, 2026
44 of 45 checks passed
@nixel2007
nixel2007 deleted the claude/perf-document-mdobject-cache branch June 21, 2026 17:34
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