Skip to content

Performance and implementation

Docs for v0.11.1 · Go 1.27.0+ · Go API

Scanning has three main costs: locating candidate patterns, verifying occurrences, and evaluating rule conditions. Result collection and file I/O add work around those stages. Which cost dominates depends on the rules and input; a large literal rule set behaves differently from a regex with frequent false candidates or a condition that hashes the whole file.

Compile once
  1. Rule sourceStrings, imports, conditions
  2. CompilerParse, type-check, select atoms
  3. Compiled programSearch tables and condition bytecode
For each input · paths depend on the patterns and conditions
  1. Find candidatesLiteral searches and prefilters
  2. Verify patternsCheck full strings, regexes, or hex patterns
  3. Evaluate conditionsUse occurrences, input bytes, and module data
A candidate can fail verification. A verified string can belong to a rule whose condition is false. Conditions can also use no strings at all.

The compiler parses rules, selects pattern-search strategies, and emits condition bytecode. It builds shared structures where patterns or assertions can be reused across rules. At scan time, necessary-condition checks can reject work early, candidate searches locate possible occurrences, and verifiers check the full pattern before its matches are used in a condition.

An atom hit is only a candidate. For example, a literal fragment from a regex may occur in the input even though the surrounding expression fails. A rule may also contain a matching string while its condition is false. These distinctions matter when interpreting throughput and match counts.

The engine selects different paths for different patterns; every scan does not run every stage. The scanner’s prefilter and evaluation code shows how these paths join.

Text patterns and eligible regex or hex atoms share an Aho–Corasick automaton. The algorithm searches multiple literals in one pass, with work proportional to the input length plus reported occurrences. This bound applies to the literal-search stage; pattern verification, condition evaluation, and result construction have separate costs. The original algorithm is described by Aho and Corasick (1975).

go-yara resolves missing automaton transitions during compilation. Scanning then uses a direct table lookup instead of walking failure links for each missing edge. Flattened tables use 16-bit state indices when the automaton has at most 65,536 states, and 32-bit indices otherwise. Dense tables reduce transition work but consume memory as the automaton grows; cache locality still matters for large rule sets.

The automaton implementation also skips runs of bytes that cannot begin a pattern when the root has a small set of possible starting bytes. The shared-pattern builder connects candidates to the rules and verifiers that need them.

The compiler looks for literal fragments that a matching regex or hex pattern must contain. Atom selection scores candidate fragments and tracks their possible offsets within the pattern. Alternatives require a complete cover: omitting a branch from the prefilter could miss a valid match. When no safe cover exists, the engine retains a more general matching path.

For eligible regexes, first-byte sets, literal suffixes before an atom, and repetition bounds narrow the candidate start positions before verification. Fixed-width byte-set sequences have a specialized verifier. General expressions use a Thompson-style NFA virtual machine, which tracks active states rather than recursively exploring backtracking paths. See Thompson (1968) for the algorithmic basis.

That design does not give every full scan a linear-time bound. Many candidate starts, broad verification windows, and large numbers of reported occurrences can still be expensive. A short common atom may save little work on repetitive data.

For eligible XOR hex patterns, adjacent byte differences provide another filter: applying the same XOR key to two bytes leaves their pairwise XOR unchanged. The scanner searches this key-independent sequence, recovers a candidate key, and verifies the full pattern. This avoids a separate full search for every key on that path.

Implementation: atom selection, byte-set and prefix analysis, regex VM, and hex and XOR matching.

The optional Go 1.27 SIMD build accelerates candidate filtering and byte operations. The implementation is architecture-specific:

Target Multi-pattern candidate filter
ARM64 NEON table lookups combine low- and high-nibble masks for up to three prefix bytes. Pattern buckets can collide, so candidates still require verification. The filter accepts 2–64 patterns.
amd64 Vector byte comparisons find possible first bytes for small pattern sets. This path accepts 2–8 patterns and at most 16 distinct starting bytes.

These limits apply to an individual automaton, not the total number of rules. Ineligible automata use the regular search path. The ARM64 filter follows the Teddy family of SIMD filtering techniques. Hyperscan author Geoff Langdale’s notes on Teddy and Harry link the dedicated papers; the Hyperscan paper describes the broader architecture. go-yara does not embed Hyperscan or implement its full regex decomposition system.

See the ARM64 filter, amd64 filter, and SIMD build instructions. Compare scalar and SIMD builds on the same CPU with the same rules.

  • Dense-root & heavy-regex prefiltering (#618–#622): Stream sorted step-1 prefilter candidate ranges in $O(1)$ memory (#618), reject non-empty fullword regex candidates before Thompson VM execution (#619), deduplicate identical StringKindHex atoms in sharedAutomaton with fanout (#620), and pre-filter hex candidates using atom-adjacent definite bytes, Tokens[0], and hexFanoutDiscriminator (#622).
  • Measured v0.11.0 → v0.11.1 CLI results (Apple M3 Max, -p 4): 256 MB dense-root (2,000 overlapping rules) improved from 28 MB/s (1.82 GiB RSS) to 144–145 MB/s (305–307 MiB RSS); 100 MB heavy regex (btc_addr + jwt_like) improved from 41–42 MB/s to 107–113 MB/s.
  • Compilation, automaton, and serialization (#546–#614): Deferred per-rule Aho–Corasick construction (CompileRule / UnmarshalCompiledProgram), sparse trie construction with byte-class compressed tables (#604), cross-rule regex/hex pattern caching (#608), semantic rule-scope/symbol-slab reuse (#613), regex.Parser reuse (#614), and zero-copy MarshalBinary/UnmarshalCompiledProgram slice handling (#612).
  • Scanning, regex, hex, and PE: Deduplicated Teddy prefix covers (up to 256 3-byte corpus groups) and 8-byte unrolled sparse scalar roots (#611), standalone $id condition lowering (#607), streaming buffer reuse (#606), regex.VMBatch reuse and lazy PE import/export indexing (#610), and direct single-jump hex scanning (#609).
  • Measured v0.10.1 → v0.11.0 results (Apple M3 Max, benchstat n=6, p=0.002): LargeCorpusCompile/rules=2000 improved by -72.2% time (143.64 → 39.92 ms) and -88.9% memory (390.16 → 43.48 MiB); LargeCorpusSerialization/Marshal/rules=2000 improved by -15.7% time and -62.5% allocs; LargeCorpusSerialization/Unmarshal/rules=2000 improved by -81.0% time (125.06 → 23.74 ms) and -91.7% memory (536.88 → 44.40 MiB); 19-benchmark High-EPS scan geomean improved by -15.4% latency (+18.2% throughput), with dense/near-miss cases improving by 26.6%–43.9%.
  • Compact prefilter fanout gating and hot-path cleanup: Non-fanout compact prefilters no longer pay a second full-automaton scan on >=256 B inputs (preserving Teddy SIMD rejection under GOEXPERIMENT=simd), ruleResultsDense clears track dirty evaluations via clearRuleResultsIfDirty(), fastSeen and prefilter hook timing skip unnecessary work, 256-byte inputs bypass redundant rootIsDense/rootCandidateCursor probes in search16/search32, and hook defer wrappers move out of MatchesWithContext, compactPrefilterRejects, and preparePatternScan (#536).
  • Measured CI scalar results (Intel(R) Xeon(R) 6975P-C vs. pre-fix main): HighEPSSelectivity/mixed improves by 62.6%–80.4% (clean 574.1 → 182.9 ns, sparse 588.8 → 191.4 ns, dense 2,329 → 870.8 ns, near_miss 1,833.5 → 359.2 ns), HighEPSParallel10K/mixed/sparse improves by 51.7% (173.7 → 83.96 ns), and the 27-benchmark gate scalar geomean improves by 45.5%, guarded going forward by TestHighEPSZeroAllocationContracts and scripts/perf_gate.sh (#536).
  • Unused module setup: The compiler caches the immutable built-in registry, semantic signatures, schemas, and function-ID bindings, and serializes only module functions referenced by each rule (#482). Text-only compilation drops from 88.47 KiB / 507 allocations to 62.57 KiB / 195 allocations on Go 1.26.9 and 1.27.3, and non-PE scans keep zero PE parser or heap overhead.
  • Entropy-weighted atom selection and two-tier prefilter gating: Prefix selection weights Shannon entropy, character-class diversity, and corpus-wide inverse document frequency, and large non-text corpora with complete shared prefilters evaluate root transitions directly before resetting pattern state (#450). In that 10,000-rule synthetic benchmark suite, saturated-atom rejection improves from 121.9 µs to 393 ns, match scans from 114.7 µs to 678 ns, and clean log prefilter rejection from 181.4 ns to 46.8 ns.
  • Borrowed evidence and streaming JSON: WithBorrowedEvidence(true) aliases Capture.Data into input slices and reuses pooled evidence containers, cutting the match-heavy evidence benchmark from 1,053 to 20 allocations/op; AppendEvidenceJSON and WriteEvidenceJSON encode findings without reflection (#449).
  • Verification, jump-scan, and serialization hotpaths: Unreachable hex jumps skip the fallback full-buffer scan, verification reuses pooled size-classed MatchContext buffers, and deterministic MarshalBinary encoding eliminates intermediate sort/map regressions (#531).

Measure these changes on your own rule corpus and input distribution; synthetic microbenchmarks do not establish uniform whole-corpus gains.

v0.9.0 introduced entropy-aware regex prefix/atom selection, bounded-class direct byte counting, experimental GOEXPERIMENT=simd prefiltering/bounded-class kernels, bounded edit-distance identifier suggestions (3.87× AMD64 / 5.20× ARM64 resilient loading), and chunked evidence storage (2,075 → 1,053 allocations/scan). See the v0.9.0 changelog for full scope and caveats.

General rule conditions execute in a bytecode interpreter. The compiler also recognizes fixed-offset integer comparisons, filesize bounds, string-at tests, string-count comparisons, and comparisons between external variables and constants. It combines these operations into fused instructions to reduce dispatch and operand-stack work.

When an entire condition consists of supported assertions joined by and, or, and not, it becomes a small dataflow program whose inputs precede their consumers. This path avoids operand-stack pushes and pops. Mixed conditions retain the general interpreter with eligible subexpressions fused. The implementation is an interpreter optimization; it does not generate native machine code.

Repeated payload and external-variable guards can share results within a scan. Early rejection is constrained by observable behavior: default scans preserve string matches even when a filesize or external condition rejects a rule, and expressions with callbacks or potentially observable errors keep normal evaluation.

The compiler also recognizes certain nested occurrence loops expressing a distance between two strings. It replaces them with a two-pointer traversal of sorted offsets. For lists of lengths m and n, the traversal takes O(m + n) rather than testing every pair. Unsorted inputs require sorting first; arbitrary nested loops do not receive this optimization.

Implementation: assertion programs, proximity recognition, and offset queries.

Use the Matches method for a boolean answer and MatchingRules for rule names and tags. Use Scan when callers need detailed outcomes and string occurrences. The result example contrasts these methods with the ScanResult.Matches occurrence map. A reusable scanner avoids repeated setup; the scanner example shows its lifetime.

WithFastScan can stop after the first occurrence of a string when the condition permits it. Rules depending on counts, offsets, or ranges still need the relevant occurrences. Keep result options the same when comparing benchmarks; omitting match details reduces the work performed.

Literal prefilters reject inputs that lack required patterns before condition evaluation. Header checks can reject rules whose required bytes are absent at fixed offsets. A warmed-up prefilter rejection can use zero heap allocations. Matches, returned results, and module calculations can still allocate.

Scanners reuse interpreter state, match storage, and scratch buffers. The convenience methods use a scanner pool; a dedicated scanner keeps reusable state within a worker. Allocation measurements should separate initial compilation, scanner warm-up, clean rejects, and positive scans. Reusing buffers can reduce allocation rate while retaining capacity, so low allocations per operation do not establish a low resident-memory footprint.

Measure clean rejects and positive matches separately. A corpus dominated by easy rejects can hide expensive behavior on repetitive data or inputs that pass a prefilter and fail later.

Repeated deterministic built-in numeric and range calls share a 16-entry cache across rules in one scan. Entries are discarded before the next scan. Once full, additional distinct calls execute normally. String arguments and time.now() bypass it.

Keys include the qualified function name, argument types, and exact argument bits, with space for up to three scalar arguments. Float keys preserve distinctions such as signed zero. Custom callbacks must explicitly opt into caching and meet the purity contract. The cache implementation uses bounded storage so a rule iterating over many different offsets cannot grow it indefinitely.

Cache hits allocate no memory, but a cache miss can allocate for the underlying calculation, such as building a digest string. Rules that request the same digest can reuse the calculation. Different arguments require separate calculations.

Run the scanner benchmarks from the repository root:

Terminal window
make bench-scan

The condition and module-cache benchmarks include variants with the optimization enabled and disabled:

Terminal window
go test ./compiler -run '^$' \
-bench '^(BenchmarkConditionDispatch|BenchmarkConditionAssertions|BenchmarkRepeatedModuleRanges)$' \
-benchmem -count=5

The v0.8.0 release notes record these development measurements on an Apple M3 Max:

Workload Baseline Optimized Scope
Condition dispatch 172.3 ns 68.7 ns Median of three paired runs, assertions disabled versus enabled.
Passing scan of 200 assertion-heavy rules 86.8 µs 62.4 µs Median of three paired runs; result details omitted.
100 rules repeating SHA-256 and entropy over 10 MiB About 654 ms, 401 allocations About 6.7 ms, 5 allocations Cache disabled versus enabled; repeated identical calls.

These measurements isolate changes within go-yara. They do not compare it with another engine. The release notes do not preserve a complete benchmark environment or raw sample set, so rerun the benchmarks for a current deployment decision. The benchmark sources specify the rules, inputs, and options: condition benchmarks and module-range benchmark.

Record the commit, Go version, build flags, CPU, rule set, and input sizes with each result. Keep those fixed when comparing changes. Report time per operation, bytes per second where meaningful, bytes allocated, and allocations per operation.

Include small and large inputs, expected matches, clean rejects, repetitive bytes, and your real rule corpus. Measure cold compilation separately from steady-state scanning. For concurrent workloads, keep the worker count fixed and use a scanner per worker.

The optional SIMD build changes some matching paths. Compare it with the scalar build on the same machine. Measure application latency separately to account for file I/O and other processing outside the scanner.

WithTelemetry updates a caller-owned ScanTelemetry sink without reading the clock. WithTelemetryLatency also measures total duration and exclusive prefilter, pattern-search, and condition-evaluation time. These phase timings and per-pattern callbacks are populated starting in v0.8.1.

WithHooks installs lifecycle, match, prefilter, rule-profile, and pattern-profile callbacks; WithRuleProfiling is a convenience option for OnRuleEvaluated. Hooks run synchronously on the scanning goroutine. Keep their work bounded, avoid blocking I/O, and do not reenter or mutate the active scanner from a callback.

One scanner and telemetry sink per worker
  1. Scan inputUpdate local counters; invoke enabled callbacks
  2. Finalize metricsUpdate totals; call completion hook on success
  3. Return and exportCheck errors; merge snapshots outside concurrent scans
Phase timers measure separate work inside the scan. Completion callbacks see final counters on success; export after the call returns to include failed attempts.
Complete Go example: collect scan metrics and hook events
main.go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
rule marker { strings: $a = "marker" condition: $a }
rule other { strings: $a = "other" condition: $a }`)
if err != nil {
return err
}
var metrics compiler.ScanTelemetry
starts, completions, matches, profiles := 0, 0, 0, 0
completionSeesFinal := false
scanner := compiler.NewScanner(program,
compiler.WithTelemetryLatency(&metrics),
compiler.WithHooks(compiler.ScanHooks{
OnScanStart: func(context.Context, int64) { starts++ },
OnScanComplete: func(context.Context, *compiler.ScanResult, time.Duration) {
completions++
completionSeesFinal = metrics.TotalScans == 2 && metrics.TotalMatches == 1 && metrics.TotalScanDurationNs > 0
},
OnPatternProfile: func(p compiler.PatternProfile) {
if p.RuleName == "marker" {
fmt.Printf("%s/%s: candidates=%d known=%t occurrences=%d\n",
p.RuleName, p.StringID, p.CandidateHits, p.CandidateHitsKnown, p.VerifiedMatches)
}
},
OnRuleEvaluated: func(compiler.RuleProfile) { profiles++ },
OnMatch: func(*compiler.CompiledRule, compiler.RuleMatch) compiler.MatchAction {
matches++
return compiler.MatchActionContinue
},
}),
)
defer scanner.Close()
for _, input := range []string{"clean", "marker marker"} {
if _, err := scanner.Scan([]byte(input)); err != nil {
return err
}
}
// Read or export the sink after Scan returns. Keep one sink per scanner.
fmt.Printf("scans=%d bytes=%d matched rules=%d\n", metrics.TotalScans, metrics.BytesScanned, metrics.TotalMatches)
fmt.Printf("starts=%d completions=%d match callbacks=%d\n", starts, completions, matches)
fmt.Printf("rule profiles received: %t\n", profiles > 0)
fmt.Printf("completion sees final metrics: %t\n", completionSeesFinal)
// Export TotalScanDurationNs, PrefilterDurationNs, PatternSearchNs, and
// ConditionEvalNs here. Exact timings vary by workload and machine.
metrics.Reset()
fmt.Printf("after reset: scans=%d bytes=%d matched rules=%d\n", metrics.TotalScans, metrics.BytesScanned, metrics.TotalMatches)
return nil
}
Output
marker/$a: candidates=2 known=true occurrences=2
scans=2 bytes=18 matched rules=1
starts=2 completions=2 match callbacks=1
rule profiles received: true
completion sees final metrics: true
after reset: scans=0 bytes=0 matched rules=0

The input contains two occurrences of marker, but TotalMatches increases by one: it counts returned public rules. Keep one sink per scanner, then merge snapshots outside concurrent scan work. The fields are ordinary mutable counters, so sharing a sink across workers requires synchronization. Reset clears the sink for the next reporting interval.

OnScanComplete sees final telemetry on successful returns, including deliberate early stops. It does not run on errors. Record failures around the scan call and export there when every attempt must be included. Boolean scans pass a nil result to the completion hook; rule-list scans supply only MatchedRules.

Measurement Interpretation and limits
TotalScans, BytesScanned Calls and supplied bytes recorded after preflight. Rejected bindings and already-cancelled contexts do not advance these counters.
TotalMatches Returned public rules accumulated across scans. Boolean Matches contributes one for true and zero for false. String occurrences are counted separately.
PrefilterRejects, RulesPruned, RulesEvaluated Work recorded by the prefilter and evaluation paths. Required-string rejection can count as an evaluated rule.
CandidateHits, VerifiedMatches, FalseCandidateHits Logical candidate hits and retained occurrences in evaluated rule contexts. False candidates sum max(candidates - occurrences, 0) where candidate counts are available; this is not a verifier failure rate.
TotalScanDurationNs Active scan time, including started attempts that fail. Excludes reader/file I/O and caller idle time between block operations. Failed attempts add no successful matches.
PrefilterDurationNs Compact/word routing and mandatory header/assertion checks.
PatternSearchNs Shared candidate generation, verification, and match-context reconstruction.
ConditionEvalNs Interpreter setup, module calls, and normal or speculative condition evaluation.
RuleProfile.ConditionSteps This rule’s loop iterations, including speculative checks. It is not a bytecode instruction count and can be zero for a condition without loops.

Phase durations are exclusive: speculative condition evaluation pauses the pattern-search timer. They need not sum to total scan time because result materialization and other work also take time. Enable latency tracking to populate duration fields; clocks and callbacks add work.

OnPrefilter reports decisions and their durations for the stages that execute. OnPatternProfile runs once for each live pattern in a completed rule match context, before the rule condition. It does not expose captured input bytes. Skipped rules, optimized-away patterns, and failed contexts have no pattern event; result materialization does not emit it again.

A pattern’s CandidateHitsKnown flag distinguishes an available candidate stream from a fallback regex/hex search that exposes no comparable count. VerifiedMatches is the retained occurrence count; boolean and fast scans can stop collecting early. Selectivity is the occurrence-to-candidate ratio when the count is known and nonzero, and zero otherwise. It is not a bounded probability. Shared cached searches contribute to each consuming rule’s profile, so their candidate counts do not measure physical verifier invocations.

Detailed, boolean, rule-list, and single-block scans use the same accounting contract. With BlockScanner, each Scan call contributes pattern-search time and pattern profiles for that block. Finish records the scan count, bytes, conditions, returned matches, and completion callback. Bytes are the sum of supplied blocks, including overlaps, rather than the logical file size. Total time combines active block calls and Finish; each additional Finish is another evaluation attempt. Reset clears accumulated block state and candidate counts; reset the telemetry sink separately when starting a new reporting interval.

Configure the hook bundle once: WithHooks replaces that bundle, including callbacks installed there by earlier convenience options.

Use profiling to locate expensive rules, then measure throughput with the intended production instrumentation; clocks and callbacks add work. See the hook definitions and scan execution paths. Hooks that change coverage are described under stopping scans from hooks.

On Unix platforms, ScanFile attempts a read-only memory mapping for regular files of at least 128 KiB. Smaller files, mapping failures, and non-Unix platforms use file reads. Mapping avoids an explicit whole-file heap copy on the supported path, but still incurs page faults, page-cache residency, and I/O. Go heap allocation statistics do not account for all of those costs. See file scanning and the mapping wrapper.

ScanReader uses a bounded sliding input window ($C+W$), while block scanning retains blocks for later condition evaluation. Accumulated occurrences, returned bytes, and evidence have separate memory costs that can grow with matches. Account for input storage as well as scanner allocations. The CLI’s literal streaming mode changes semantics; use it only when text-pattern occurrences are the output you need.

The comparison with libyara and YARA-X covers execution models, Go integration, and module coverage. Aho–Corasick searching and atom-based filtering are shared techniques; their presence alone does not predict which engine will be faster on a particular corpus.

A cross-engine benchmark needs the same accepted rules, input bytes, requested match details, worker count, timeout policy, and file-cache conditions. Check matched rules and required occurrences first. Record rejected rules and timeouts alongside timings, and separate compilation from repeated scanning. The measurements above do not establish a cross-engine ranking.