惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Hacker News
The Hacker News
Martin Fowler
Martin Fowler
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
F
Full Disclosure
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recorded Future
Recorded Future
Security Archives - TechRepublic
Security Archives - TechRepublic
阮一峰的网络日志
阮一峰的网络日志
T
Threatpost
P
Privacy International News Feed
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
I
Intezer
Recent Announcements
Recent Announcements
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Privacy & Cybersecurity Law Blog
A
Arctic Wolf
博客园 - 聂微东
博客园 - 叶小钗
Cisco Talos Blog
Cisco Talos Blog
H
Help Net Security
S
Schneier on Security
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
The Exploit Database - CXSecurity.com
T
Tor Project blog
月光博客
月光博客
NISL@THU
NISL@THU
A
About on SuperTechFans
Spread Privacy
Spread Privacy
Blog — PlanetScale
Blog — PlanetScale
D
DataBreaches.Net
雷峰网
雷峰网
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
G
Google Developers Blog
W
WeLiveSecurity
P
Palo Alto Networks Blog
The Last Watchdog
The Last Watchdog
K
Kaspersky official blog
博客园 - 司徒正美
L
LINUX DO - 热门话题
小众软件
小众软件

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
"How I Cut My Go Markdown Linter's Benchmark by 81%"
Kazu · 2026-05-26 · via DEV Community

When I started optimizing gomarklint, I had no benchmarks. I had unit tests. I had coverage. But I had no idea what the linter actually cost to run on a real document.

Here's what I found, what I changed, and what I'd do differently next time.

What is gomarklint?

gomarklint is a Go-based CLI Markdown linter I've been building as an open-source project. The pitch: catch broken links before your readers do, keep your Markdown clean, single binary, no Node.js required.

The main alternative most teams reach for is markdownlint, which works well but requires a Node.js runtime. For Go projects running in a lean CI environment, pulling in Node.js just to lint Markdown felt like the wrong tradeoff. gomarklint ships as a standalone binary installable via Homebrew, npm, or go install, and integrates with GitHub Actions and pre-commit out of the box.

The rule set covers around 25 checks: structural rules like heading-level (no H4 appearing under H2 without an H3 in between), content rules like no-bare-urls and fenced-code-language, and link validation including internal anchor checking. Each rule emits diagnostics with file path, line number, and severity — error causes a non-zero exit, making it safe as a CI gate.

Internally, each rule is a function that receives the full file content as a slice of lines and returns a slice of violations. No shared parse tree, no AST, just functions over strings. That made it easy to add rules quickly.

The current release processes 100,000+ lines in under 170ms. A typical 200-line README lints in under 0.2 ms across all rules, and a large documentation site with hundreds of files fits in a CI step nobody notices. Getting there required 20 PRs over three weeks, each measured before it merged.

The Starting Point: No Visibility

gomarklint's rules like heading-level, no-bare-urls, fenced-code-language, and around 25 others each receive the full file content split into lines and return a slice of violations. Rules run independently, no shared parse tree, no AST, just functions over strings.

That architecture is easy to extend. But every rule doing anything non-trivial had to solve the same problem on its own: "is this line inside a code block?" Headings inside fenced blocks aren't real headings. URLs inside fenced blocks aren't real URLs. Every rule that cared had to figure it out independently.

The solution that grew organically was a shared utility called GetCodeBlockLineRanges. It scanned the entire document, built a list of [start, end] line ranges for every fenced block, and returned them. Any rule could then call isInCodeBlock(lineNumber, ranges) to check membership via a linear search.

I didn't notice this was a problem because I never measured it.

Step 1: Build a Benchmark You Can Trust

Before optimizing anything, I needed a benchmark I could actually rely on. The existing per-rule _bench_test.go files were isolated and not included in CI comparisons, so they gave no signal about end-to-end cost.

I rewrote the benchmark around a single generateComplexMarkdown(n int) function that produces a realistic n-section document (headings, paragraphs, lists, fenced code blocks, images, links) exercising every rule's scan path without producing any violations:

func writeIntro(sb *strings.Builder) {
    sb.WriteString("# Main Title\n\n")
    sb.WriteString("This is the introduction to the document.\n\n")
}

func writeHeading(sb *strings.Builder, i int) {
    fmt.Fprintf(sb, "## Section %d\n\n", i)
}

func writeParagraph(sb *strings.Builder) {
    sb.WriteString("This section contains *important* information. ")
    sb.WriteString("Here are some **key** details that you should know about.\n\n")
}

func writeList(sb *strings.Builder) {
    sb.WriteString("Key points:\n\n")
    sb.WriteString("- First important point\n")
    sb.WriteString("- Second critical detail\n")
    sb.WriteString("- Third consideration\n\n")
}

func writeCodeBlock(sb *strings.Builder) {
    sb.WriteString("```

go\n")
    sb.WriteString("func example() error {\n")
    sb.WriteString("    return nil\n")
    sb.WriteString("}\n")
    sb.WriteString("

```\n\n")
}

func writeLinks(sb *strings.Builder, i int) {
    sb.WriteString("Useful resources:\n\n")
    fmt.Fprintf(sb, "- [Documentation](https://example.com/docs/%d)\n", i)
    fmt.Fprintf(sb, "- [GitHub](https://github.com/project/%d)\n", i)
    sb.WriteString("\n")
}

func writeImage(sb *strings.Builder, i int) {
    fmt.Fprintf(sb, "![Diagram %d](diagram%d.png)\n\n", i, i)
}

func writeSubsection(sb *strings.Builder, i int) {
    fmt.Fprintf(sb, "### Subsection %d.1\n\n", i)
    sb.WriteString("More detailed information goes here.\n\n")
}

func generateComplexMarkdown(sections int) string {
    var sb strings.Builder
    writeIntro(&sb)
    for i := 1; i <= sections; i++ {
        writeHeading(&sb, i)
        writeParagraph(&sb)
        writeList(&sb)
        if i%2 == 0 {
            writeCodeBlock(&sb)
        }
        if i%3 == 0 {
            writeLinks(&sb, i)
        }
        if i%4 == 0 {
            writeImage(&sb, i)
        }
        writeSubsection(&sb, i)
    }
    result := sb.String()
    return result[:len(result)-1]
}

Enter fullscreen mode Exit fullscreen mode

That last constraint — zero violations — matters. A benchmark that triggers violations measures error-reporting cost, not scanning cost. I added a guard test to enforce it:

func TestBenchmarkContentIsViolationFree(t *testing.T) {
    content := generateComplexMarkdown(1000)
    results, err := lint.LintContent(content, benchmarkConfig())
    require.NoError(t, err)
    assert.Empty(t, results)
}

Enter fullscreen mode Exit fullscreen mode

This test runs in CI on every PR in the series. If anyone accidentally adds a violation to the benchmark content, the build breaks before the numbers become meaningless.

The benchmark also pays forward. Now that it runs on every PR, any new rule added to gomarklint gets automatically checked for performance regression before it merges. If a new no-trailing-spaces rule adds 15% to the geomean, benchstat surfaces that number in the PR diff — before it ships, not after. Without a benchmark in CI, performance regressions from new features are invisible until someone notices the linter "feels slower" on a large repo.

Step 2: Profile Before Touching Anything

With the benchmark in place, I ran a CPU and allocation profile against the 1000-section document:

go test -bench=BenchmarkFullLinting -benchtime=5s \
    -cpuprofile=cpu.prof -memprofile=mem.prof ./cmd/
go tool pprof -top cpu.prof

Enter fullscreen mode Exit fullscreen mode

The top result:

Showing top 5 nodes out of 42
      flat  flat%   sum%        cum   cum%
   6.32s  63.72% 63.72%      6.32s 63.72%  isInCodeBlock
   0.89s   8.97% 72.69%      0.89s  8.97%  strings.TrimSpace
   0.54s   5.44% 78.14%      0.54s  5.44%  regexp.(*Regexp).FindStringSubmatch
   ...

Enter fullscreen mode Exit fullscreen mode

isInCodeBlock was a shared helper called from multiple rules. Each call invoked GetCodeBlockLineRanges, which allocated a [][2]int slice by scanning the entire document to find fence boundaries, then performed a linear search through that slice to answer one question: "is line N inside a code block?"

That's O(n × k) per rule per line, where n is the number of lines and k is the number of code blocks. In a document with 6 rules calling it and 50 code blocks, every line triggered 6 linear searches over 50 ranges. The cost multiplied silently across every rule that wanted to skip code block content.

The allocation profile added a second finding: CheckHeadingLevels was calling regexp.MustCompile(atxHeadingPattern) inside the function body on every invocation — not once at package init. That single oversight was allocating ~16 MB of heap per benchmark run and showed up clearly in -memprofile output.

Step 3: Fix the Biggest Problem First

Both issues were in the heading-level rule. I fixed them together in PR #182:

Before:

func CheckHeadingLevels(filename string, lines []string, offset int, minLevel int) []LintError {
    var errs []LintError
    prevLevel := 0
    headingRegex := regexp.MustCompile(`^(#{1,6})\s+`) // compiled on every call
    codeBlockRanges, _ := GetCodeBlockLineRanges(lines) // O(n) alloc

    for i, line := range lines {
        if isInCodeBlock(i+1, codeBlockRanges) { // O(k) linear search per line
            continue
        }
        matches := headingRegex.FindStringSubmatch(line)
        if matches != nil {
            currentLevel := len(matches[1])
            // ... violation checks
            prevLevel = currentLevel
        }
    }
    return errs
}

Enter fullscreen mode Exit fullscreen mode

After:

// atxHeadingLevel returns the heading level (1–6) or 0.
// Pure byte scan — no regex, no allocation.
func atxHeadingLevel(line string) int {
    level := 0
    for level < len(line) && line[level] == '#' {
        level++
    }
    if level == 0 || level > 6 {
        return 0
    }
    if level == len(line) || line[level] == ' ' || line[level] == '\t' {
        return level
    }
    return 0
}

func CheckHeadingLevels(filename string, lines []string, offset int, minLevel int) []LintError {
    var errs []LintError
    prevLevel := 0
    inCodeBlock := false
    var fenceMarker string

    for i, line := range lines {
        if len(line) == 0 {
            continue
        }
        first := firstNonSpaceByte(line)

        // Inline fence tracking — no allocation, no O(n×k) lookup.
        if inCodeBlock {
            if first == fenceMarker[0] {
                trimmed := strings.TrimSpace(line)
                if IsClosingFence(trimmed, fenceMarker) {
                    inCodeBlock = false
                    fenceMarker = ""
                }
            }
            continue
        }

        if first != '#' && first != '`' && first != '~' {
            continue
        }

        trimmed := strings.TrimSpace(line)
        if marker := openingFenceMarker(trimmed); marker != "" {
            inCodeBlock = true
            fenceMarker = marker
            continue
        }
        if first != '#' {
            continue
        }

        currentLevel := atxHeadingLevel(trimmed)
        if currentLevel == 0 {
            continue
        }
        // ... violation checks
        prevLevel = currentLevel
    }
    return errs
}

Enter fullscreen mode Exit fullscreen mode

The result on CI (AMD EPYC, 1000-section document):

metric before after delta
time/op (geomean) 52.55 ms 14.78 ms −72%
memory/op 2.108 Mi 1.912 Mi −9%
allocs/op 9,225 4,677 −49%

One PR. 72% of the time gone.

Step 4: Turn the Pattern Into a System

The heading-level fix revealed a reusable pattern: the firstNonSpaceByte prefilter. Most rules only care about lines starting with a specific byte. A heading starts with #. A fenced code block starts with ` or ~. A hard tab starts with \t.

Reading the first non-whitespace byte costs almost nothing — one loop over leading spaces, then a byte read. Calling strings.TrimSpace on every line is not free, especially when 95% of lines would be skipped anyway.

I applied this prefilter across 14 more rules over 14 subsequent PRs:

func firstNonSpaceByte(s string) byte {
    for i := 0; i < len(s); i++ {
        c := s[i]
        if c != ' ' && c != '\t' && c != '\r' && c != '\n' {
            return c
        }
    }
    return 0
}

Enter fullscreen mode Exit fullscreen mode

Each individual PR produced a modest gain — 3% to 15% per rule. But they compounded:

PR Rule time delta
#193 no-bare-urls −15.5%
#195 no-emphasis-as-heading −8.8%
#190 empty-alt-text −6.4%
#194 duplicate-heading −3.0% (+ −12.6% memory)
#192 no-empty-links −2.8%

The Final Numbers

Starting from the benchmark baseline after the scaffolding work, to the last PR in the series:

metric start end improvement
time/op (geomean) 74.37 ms 13.88 ms −81%
memory/op 2.221 Mi 1.654 Mi −25%
allocs/op 9,533 4,510 −53%

Twenty PRs over three weeks. Each one measured, each one merged only after the CI benchmark comparison confirmed no regression.

What I'd Do Differently

Profile before writing a single optimization. I got lucky that the biggest problem (isInCodeBlock at 63%) was immediately obvious. In a more complex codebase, guessing the hotspot first would have sent me optimizing rules that contributed 0.5% of total CPU while the real bottleneck sat untouched. The 20-minute setup cost of a proper benchmark pays back on the first targeted fix.

Treat the benchmark content as a first-class artifact. A benchmark that produces violations is measuring error-reporting cost, not scanning cost. A benchmark whose content drifts rule-by-rule becomes impossible to interpret. The TestBenchmarkContentIsViolationFree guard test caught three cases mid-series where a content addition accidentally triggered a violation. Without it, I would have been optimizing against corrupted numbers and wondering why the geomean kept moving.

Two PRs in this series landed within measurement noise. One was closed without merging. Having numbers in each PR body made that obvious: the CI benchstat output showed ~ (p=0.485) and there was nothing to argue about. A single "performance" PR with twenty changes mixed together would have buried those non-results.

Writing before/after benchmark numbers in every PR description did something I didn't expect: it made the series reviewable after the fact. Looking back at 20 PRs, I can tell exactly which optimization accounted for which fraction of the total gain. The firstNonSpaceByte prefilter was worth applying to 14 rules because I could see, rule by rule, that it kept working. That's how I found the pattern in the first place.

Try It

gomarklint is open source: github.com/shinagawa-web/gomarklint. The entire optimization series is tracked under issue #146, with each PR linking back to it and carrying its own before/after benchmark numbers.

If you're running a Go linter or any line-by-line text processor, these two patterns are worth trying before anything fancier: inline fence tracking instead of pre-computed ranges, and a first-byte prefilter before any string work. Zero dependencies, easy to test, and between them they accounted for almost all of the 81%.