Logo di Skill Performance

Skill Performance

Community
javiarmesto
skill-performance

AL performance optimization patterns for Business Central. Use when optimizing queries with SetLoadFields, working with FlowFields and CalcFields, profiling codeunits, or resolving performance issues.

Add to TypingMind

Panoramica

Pubblicato dajaviarmesto
RepositoryALDC-AL-Development-Collection
Nome della skillskill-performance
Stelle
115
Fork
37
File inclusi
Solo istruzioni
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da javiarmesto su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Skill Performance in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/javiarmesto/ALDC-AL-Development-Collection/tree/main/.claude/skills/skill-performance
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/javiarmesto/ALDC-AL-Development-Collection.git /tmp/ALDC-AL-Development-Collection
mkdir -p .claude/skills
cp -r /tmp/ALDC-AL-Development-Collection/.claude/skills/skill-performance .claude/skills/skill-performance
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Skill Performance in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Skill Performance non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Skill Performance non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

Skill: AL Performance Optimization

Purpose

Identify, analyze, and fix performance bottlenecks in AL code: inefficient queries, FlowField issues, loop anti-patterns, and data-volume problems in Business Central.

When to Load

This skill should be loaded when:

  • A page, report, or batch process is slow or timing out
  • CPU profiling is needed to identify hotspots
  • A static triage of the codebase is requested for performance issues
  • A feature involves large-dataset processing or high-frequency code paths
  • AL0896 (circular FlowField) errors appear
  • Architecture review requires performance analysis of a new design

Core Patterns

For BC29 query or isolated-storage concurrency work, read the query/storage sections of AL18 capability checks. Confirm supported declarations and test transaction behavior before changing isolation; DataScope and transaction isolation are different concepts.

Pattern 1: SetLoadFields + Early Filtering

Always filter before finding, and load only needed fields. Order matters.

al
// ✅ Correct: SetRange first, SetLoadFields before Find
Item.SetRange("Third Party Item Exists", false);
Item.SetLoadFields("Item Category Code", Description);
if Item.FindSet() then
    repeat
        // Only "Item Category Code" and Description loaded from DB
    until Item.Next() = 0;

// ❌ Wrong: SetLoadFields after SetRange (ignored), loads all fields
Item.SetLoadFields("Item Category Code");
Item.SetRange("Third Party Item Exists", false);
Item.FindFirst();

// ❌ Wrong: No filter — full table scan
procedure GetCustomersByCity(CityFilter: Text): Integer
var
    Customer: Record Customer;
    Count: Integer;
begin
    if Customer.FindSet() then       // loads entire Customer table
        repeat
            if Customer.City = CityFilter then
                Count += 1;
        until Customer.Next() = 0;
end;

// ✅ Correct: Filter pushed to DB
procedure GetCustomersByCity(CityFilter: Text): Integer
var
    Customer: Record Customer;
begin
    Customer.SetRange(City, CityFilter);
    Customer.SetRange(Blocked, Customer.Blocked::" ");
    exit(Customer.Count());
end;

Pattern 2: Set-Based Aggregation (CalcSums / CalcFields)

Avoid manual loops for aggregation — push the sum to the database.

al
// ❌ Loop accumulation — N rows fetched and processed in AL
procedure GetTotalSales(CustomerNo: Code[20]): Decimal
var
    Entry: Record "Cust. Ledger Entry";
    Total: Decimal;
begin
    Entry.SetRange("Customer No.", CustomerNo);
    if Entry.FindSet() then
        repeat
            Total += Entry.Amount;
        until Entry.Next() = 0;
    exit(Total);
end;

// ✅ CalcSums — single aggregation query at DB level
procedure GetTotalSales(CustomerNo: Code[20]): Decimal
var
    Entry: Record "Cust. Ledger Entry";
begin
    Entry.SetRange("Customer No.", CustomerNo);
    Entry.CalcSums(Amount);
    exit(Entry.Amount);
end;

For FlowFields accessed outside a page context, always call CalcFields before reading:

al
Customer.SetLoadFields("Balance (LCY)");
Customer.Get(CustomerNo);
Customer.CalcFields("Balance (LCY)");   // required — not auto-calculated in code

Pattern 3: Temporary Tables / Dictionary / List

Pre-load data once, then process in-memory multiple times.

al
// ✅ Temporary table — structured record data, multi-pass processing
procedure ProcessSalesData(var TempSalesLine: Record "Sales Line" temporary)
var
    SalesLine: Record "Sales Line";
begin
    SalesLine.SetLoadFields("No.", Quantity, "Unit Price", Amount);
    if SalesLine.FindSet() then
        repeat
            TempSalesLine := SalesLine;
            TempSalesLine.Insert();
        until SalesLine.Next() = 0;

    // Process in-memory — zero additional DB hits
    ApplyDiscounts(TempSalesLine);
    CalculateTotals(TempSalesLine);
end;

// ✅ Dictionary — key-value lookup cache
procedure CacheCustomerNames(): Dictionary of [Code[20], Text]
var
    Customer: Record Customer;
    Cache: Dictionary of [Code[20], Text];
begin
    Customer.SetLoadFields("No.", Name);
    if Customer.FindSet() then
        repeat
            Cache.Add(Customer."No.", Customer.Name);
        until Customer.Next() = 0;
    exit(Cache);
end;

// ✅ List — simple value collection
procedure GetBlockedCustomerNos(): List of [Code[20]]
var
    Customer: Record Customer;
    Result: List of [Code[20]];
begin
    Customer.SetRange(Blocked, Customer.Blocked::All);
    Customer.SetLoadFields("No.");
    if Customer.FindSet() then
        repeat
            Result.Add(Customer."No.");
        until Customer.Next() = 0;
    exit(Result);
end;

Pattern 4: Batch Processing and Avoiding Nested DB Calls

Move database operations outside loops; batch writes.

al
// ❌ Nested DB call inside loop — O(n²) database hits
if MainTable.FindSet() then
    repeat
        OtherTable.SetRange(Field, MainTable.Field);
        if OtherTable.FindSet() then          // DB call per iteration
            repeat
                // process
            until OtherTable.Next() = 0;
    until MainTable.Next() = 0;

// ✅ Pre-load into temp table, then join in memory
if OtherTable.FindSet() then
    repeat
        TempOther := OtherTable;
        TempOther.Insert();
    until OtherTable.Next() = 0;

if MainTable.FindSet() then
    repeat
        if TempOther.Get(MainTable.Field) then
            // process — no DB hit
    until MainTable.Next() = 0;

Batch writes — collect changes, write once:

al
// ✅ Calculate all values first, then single Modify
procedure UpdateCustomerStats(CustomerNo: Code[20])
var
    Customer: Record Customer;
    TotalBalance: Decimal;
    LastPaymentDate: Date;
begin
    CalculateCustomerTotals(CustomerNo, TotalBalance, LastPaymentDate);

    Customer.SetLoadFields("Balance (LCY)", "Last Payment Date");
    if Customer.Get(CustomerNo) then begin
        Customer."Balance (LCY)" := TotalBalance;
        Customer."Last Payment Date" := LastPaymentDate;
        Customer.Modify(true);   // single write
    end;
end;

Scale-aware processing:

al
procedure UpdatePricesForItems(var Item: Record Item)
begin
    if Item.Count() > 1000 then
        UpdatePricesInBatches(Item)    // job queue / chunked
    else
        UpdatePricesDirectly(Item);
end;

Pattern 5: FlowField Optimization (AL0896)

Circular FlowField references cause infinite evaluation (AL0896 error):

❌ Circular dependency:
Table Customer: FlowField "Total Sales" → CalcFormula from Sales Statistics
Table Sales Statistics: FlowField "Customer Balance" → CalcFormula from Customer

Compiler error AL0896: recursive dependency detected

Resolution strategies (in order of preference):

  1. Break the chain — convert one FlowField to a regular field updated via trigger
  2. Use CalcSums — replace FlowField with explicit CalcSums in code
  3. Restructure — move the calculation to a dedicated codeunit called on demand
  4. SumIndexFields — use SIFT keys for frequently summed values

Avoid FlowFields:

  • With complex nested CalcFormula expressions
  • Called inside repeat...until loops (call CalcFields once, outside loop if possible)
  • Where the source table is large and unfiltered

Workflow

Step 1: Triage (Static Code Analysis)

Scan the codebase before profiling to identify structural issues:

Patterns to detect manually or with search + problems:

  • FindSet() / FindFirst() without preceding SetRange / SetFilter
  • SetLoadFields placed after SetRange (wrong order)
  • Database calls (Get, FindSet, FindFirst) inside repeat...until
  • CalcFields inside loops
  • FlowField CalcFormula referencing tables that reference back (AL0896)
  • Commit inside loops (locks + performance risk)
  • Missing keys for columns used in SetRange

Severity assessment:

  • 🔴 Critical — DB call in loop over large table, circular FlowField, timeout-causing query
  • 🟡 High — Missing SetLoadFields in high-frequency path, nested loops
  • 🟢 Medium — Suboptimal aggregation (loop instead of CalcSums)
  • 🔵 Low — Best-practice suggestion, minimal current impact

Step 2: Profile (Runtime Measurement)

Generate CPU profile for runtime bottleneck identification:

Capture a CPU profile in VS Code (VS Code command — not an agent tool)

Analyze profile for:

  • Hotspots — procedures with highest cumulative execution time
  • Frequency — procedures called most often (especially in loops)
  • DB operations — expensive FindSet / Get calls
  • FlowField evaluations — unexpectedly costly CalcFields

Compare before/after optimizations by re-profiling after each fix.

⚠️ Human Gate — cleanup: Before clearing codelenses, confirm all findings are documented:

Clear profile codelenses in VS Code  ← VS Code command (not an agent tool), only after approval

Step 3: Fix

Apply fixes in priority order (critical first). For each fix:

  1. Apply targeted change (Pattern 1–5 above)
  2. Rebuild: al_build
  3. Re-profile to verify improvement

Performance targets:

MetricTarget
Page load< 2 seconds
Report generation< 10 seconds (standard dataset)
API response< 500 ms
Batch processing> 1,000 records/minute

Step 4: Document Findings

For significant optimizations, create a triage report at .claude/plans/perf-triage-<scope>.md:

markdown
# Performance Triage — <Scope>

**Date**: YYYY-MM-DD
**Analyzed**: [path or objects]

## Findings

| Severity | Location | Issue | Recommendation |
|---|---|---|---|
| 🔴 | `File.al:42` | Nested DB call in loop | Pre-load into TempTable |
| 🟡 | `File.al:87` | Missing SetLoadFields | Add SetLoadFields("No.", Name) |

## Changes Applied

1. [Change] — before/after metric
2. [Change] — before/after metric

## Remaining Items

[Issues not yet fixed, prioritized]

⚠️ Human Gate — report: Review findings before saving; confirm no sensitive code patterns are exposed.

References

Constraints

  • This skill covers analysis and fix patterns — it does NOT duplicate the passive rules in al-performance.instructions.md (auto-applied to all .al files)
  • Do NOT modify source code automatically during triage — generate report and get approval first
  • Do NOT clear profile codelenses without human confirmation
  • Do NOT save triage report without human gate review
  • For runtime debugging of a specific issue (breakpoints, snapshots) → load skill-debug.md
  • For event subscriber performance issues → load skill-events.md

Domande frequenti

Cosa fa la skill IA Skill Performance?

AL performance optimization patterns for Business Central. Use when optimizing queries with SetLoadFields, working with FlowFields and CalcFields, profiling codeunits, or resolving performance issues.

Perché usare Skill Performance su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Skill Performance è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Skill Performance in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/javiarmesto/ALDC-AL-Development-Collection/tree/main/.claude/skills/skill-performance. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Skill Performance?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Skill Performance?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Skill Performance: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Skill Performance è gratuita?

Sì. È pubblicata su GitHub da javiarmesto con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇