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

推荐订阅源

月光博客
月光博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
IT之家
IT之家
Cyberwarzone
Cyberwarzone
T
Troy Hunt's Blog
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
T
Threat Research - Cisco Blogs
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
G
GRAHAM CLULEY
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 叶小钗
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes
The Hacker News
The Hacker News
Jina AI
Jina AI
T
Tor Project blog
V
Vulnerabilities – Threatpost
酷 壳 – CoolShell
酷 壳 – CoolShell
Spread Privacy
Spread Privacy
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Simon Willison's Weblog
Simon Willison's Weblog
Security Latest
Security Latest
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 司徒正美
V2EX - 技术
V2EX - 技术
I
Intezer
The Cloudflare Blog
Cisco Talos Blog
Cisco Talos Blog
SecWiki News
SecWiki News
博客园 - 【当耐特】
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
Lohrmann on Cybersecurity
Scott Helme
Scott Helme
Google Online Security Blog
Google Online Security Blog
量子位
The Last Watchdog
The Last Watchdog
AI
AI
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security Affairs
P
Palo Alto Networks Blog
S
Secure Thoughts
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Attack and Defense Labs
Attack and Defense Labs

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
fastjson 0.3.0: A Faster Drop-In ext/json for PHP, Backed by yyjson
Ilia Alshane · 2026-05-20 · via DEV Community

Ilia Alshanetsky

// Before
$payload = json_encode($response);
$data    = json_decode($input, true);
$ok      = json_validate($input);

// After
$payload = fastjson_encode($response);
$data    = fastjson_decode($input, true);
$ok      = fastjson_validate($input);

Enter fullscreen mode Exit fullscreen mode

That's the migration. Search-and-replace json_* for fastjson_*. JSON flags, error constants, and last-error semantics carry across byte-for-byte. The two extensions sit next to each other in the same process; adoption is per call site, not per repo.

On the simdjson_php canonical 14.8 MB corpus, that swap buys 6.06× encode throughput, 2.66× decode, and 5.10× validate against ext/json on the same PHP 8.6.0-dev build. The repo is at github.com/iliaal/fastjson. 0.3.0 shipped yesterday.

Why drop in faster JSON for PHP

ext/json is fine. It's correct, well-maintained, and tracks the spec. On low-traffic endpoints it isn't on anyone's profiler. The cost shows up at scale: any application that calls json_encode and json_decode on every request path eventually finds JSON serialization sitting at the top of a flame graph. API gateways feel it first, then log processors and microservice fan-out paths.

Before fastjson the practical options were two:

  1. Stay on ext/json. Eat the CPU cost.
  2. Reach for simdjson_php. It's fast but decode-only and not API-compatible; every call site has to be rewritten around its result shape.

fastjson is option three. It's a native PHP extension that wraps yyjson 0.12.0 (MIT, ~6K LOC of focused C) behind a namespaced API that mirrors ext/json's contract. PHP 8.3 minimum; 8.4 and 8.5 supported; coexists with ext/json.

What "drop-in" actually means here

The risk with any "drop-in" claim is that it covers 90% of cases and silently changes behavior on the 10% that matter. So this section is what fastjson does and what it doesn't:

  • Function signatures track ext/json. fastjson_encode($value, int $flags = 0, int $depth = 512). Same positional shape. Same defaults. Same return values on success, false on failure.
  • JSON_* flags match byte-for-byte. JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT, the JSON_HEX_* family, JSON_THROW_ON_ERROR, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE. The integer constants are intentionally identical so user code can pass the same flag value into either function.
  • JSON_ERROR_* codes match byte-for-byte, messages don't. fastjson_last_error() returns the same JSON_ERROR_* int as json_last_error() for the same failure class, so code branching on error codes works without modification. fastjson_last_error_msg() returns yyjson's parser message (e.g., "unexpected character"), not ext/json's. Application code that pattern-matches on the message string needs updating; code that branches on the code does not.
  • Coexistence, not replacement. Both extensions load. Migrate the call sites where JSON is on the hot path; leave the rest on ext/json.
  • 53 phpt tests rewritten from php-src/ext/json/tests/*.phpt run alongside fastjson's own suite. The rest of the upstream suite is categorized in tests/upstream-json/.skiplist with the reason each test was deferred (most are tests of ext/json internals that don't translate, a few hit known divergences).
  • Documented divergences. Large/scientific doubles emit 100000000000000000.0 where ext/json emits 1.0e+17 in some ranges. U+2028 / U+2029 line separators emit as ordinary code points; ext/json always escapes them for JSONP safety. Both divergences are in the skiplist with rationale.

The numbers

Full simdjson_php canonical corpus: 14.8 MB across 15 files, the same set the simdjson PHP binding has been benchmarked against for years. Hardware: i9-13950HX. PHP 8.6.0-dev, release build (-O2). fastjson built -O2 against the same PHP. yyjson 0.12.0 with three local patches. Numbers in throughput, MB/sec:

Operation fastjson ext/json Speedup
Decode (stdClass) 602 MB/s 227 MB/s 2.66×
Decode (assoc array) 628 MB/s 237 MB/s 2.65×
Encode 1,092 MB/s 180 MB/s 6.06×
Validate 1,352 MB/s 265 MB/s 5.10×

Visual side-by-side, including ext/json with Nora Dossche's open SIMD encode work (php-src#17734) and simdjson_php on the same PHP 8.6.0-dev build, lives at https://iliaal.github.io/fastjson/baseline.html. Reproduce locally with bench/run.php against any PHP install.

The encode speedup is the largest gap because the PHP-native encoder has the most room to give back. ndossche's php-src#17734 patch closes a meaningful chunk of that gap inside ext/json itself using SIMD on string encoding. fastjson and that PR attack the same problem from different angles, and an application can benefit from both once #17734 lands upstream (fastjson re-baselines automatically; the visual page already shows both).

How the encoder gets to 6×

The encoder is one-stage. A zval walks straight into a smart_str buffer via yyjson's writer primitives. There's no intermediate DOM, no two-pass build-then-serialize, no temporary string allocations for the common-case scalars. Each PHP value type maps to one or two yyjson calls; arrays and objects walk recursively into the same path.

A few less-obvious pieces:

  • Custom allocator wired through Zend. yyjson's allocator hooks route every alloc/realloc/free through PHP's emalloc family. JSON workloads count against memory_limit and against per-request memory accounting; oversized inputs bail out the same way any other PHP allocation does.
  • Direct smart_str integration. No RETURN_STRING(estrdup(buf)) after a separate allocation. The yyjson writer writes into the smart_str.s backing store, which becomes the return zend_string directly. One allocation per encode call in the common case.
  • HEX_* flag scan-first. The flags JSON_HEX_TAG/HEX_AMP/HEX_APOS/HEX_QUOT rewrite specific characters into hex escapes. fastjson scans the string once for any candidate character; if none are present, the rewrite path is skipped entirely and the string is encoded directly. Defensive callers that pass HEX_* flags as a precaution on payloads that don't actually contain the substituted characters don't pay the rewrite cost.
  • Integer-valued-double shortcut. When a double round-trips losslessly through int64, fastjson emits it as an integer without going through php_gcvt or yyjson's REAL writer. A cheap range check fires before floor(), so number-heavy arrays of non-integer doubles don't pay libm per element.

The decode path's gain has different sources: yyjson itself, which parses with less branching and tighter memory locality than ext/json's parser, and a local yyjson patch (YYJSON_READ_VALIDATE_ONLY) that turns the read path into a fast validate-only mode without materializing values.

The memory tradeoff

Worth surfacing before anyone hits it in production. Decode and validate hold the yyjson document object in memory alongside the PHP-side result, because yyjson's value graph is built first, then traversed to produce zvals. Peak heap on decode is roughly 1.7× what ext/json peaks at on the same input. Encode is one-stage and peaks at ~1.06× of ext/json.

Validate is the loudest: peak heap is ~101× ext/json's streaming validator (which sits at a constant ~80 bytes since it doesn't materialize anything). The headline number sounds extreme, but the absolute footprint is bounded by yyjson's read path, and it's already 2.7× lower than yyjson's stock read path thanks to a vendored validate-only patch (YYJSON_READ_VALIDATE_ONLY) that skips the value-graph build.

For most callers, the speedup wins. If the application is validate-heavy on giant inputs under tight memory_limit, the memory profile is a real consideration. The right move there is to leave validate-on-huge-inputs on ext/json and migrate the encode and decode paths. That's exactly what coexistence buys.

Compat harness

53 rewritten phpt tests from php-src/ext/json/tests/*.phpt run alongside fastjson's native suite. They cover the common decode/encode/validate paths, the flag combinations, and the documented error conditions.

The two remaining intentional divergences:

  • Large/scientific doubles. Outside the integer-valued-double shortcut range, fastjson emits yyjson's real-number format. ext/json uses php_gcvt and switches to scientific notation earlier. The disagreement window narrowed in 0.3.0; what's left is the genuinely-fractional case where yyjson and php_gcvt produce different decimal representations of the same IEEE 754 double.
  • U+2028 / U+2029 line separators. ext/json always escapes these for JSONP safety. yyjson treats them as ordinary code points. fastjson follows yyjson's behavior. If JSONP is in the deployment path, set JSON_UNESCAPED_UNICODE off in ext/json and stay on ext/json for that endpoint, or wrap fastjson output through a JSONP-safe post-step.

Upstream collaboration with yyjson

fastjson vendors yyjson 0.12.0 with three local patches. Full details are in vendor/yyjson/PATCHES.md; the short version of each, and what happened when each was proposed upstream:

  • Lowercase hex digits in \uXXXX escape table. yyjson emits uppercase; ext/json emits lowercase. RFC 8259 §7 allows either, but byte-parity with ext/json is the project's compat goal. Proposed as yyjson#264 (YYJSON_WRITE_LOWERCASE_HEX flag) and accepted upstream on 2026-05-11. fastjson will drop this patch once the vendored sources advance past yyjson 0.12.0.
  • YYJSON_READ_VALIDATE_ONLY, no-tree validate mode. Forks yyjson's parser entry point to skip the value-graph build entirely; peak memory drops 2.7× on the validate corpus. Not yet proposed upstream; the API surface needs a round of review before it's ready to submit.
  • Public yyjson_write_string_to_buf() wrapper. Exposes yyjson's internal direct-write primitive so fastjson's one-stage encoder can compose at the buffer level. Proposed as yyjson#266 and closed upstream; the maintainer preferred to keep that surface private. The wrapper stays vendored locally; fastjson lives with it indefinitely.

Install

pie install iliaal/fastjson

Enter fullscreen mode Exit fullscreen mode

Or build from source:

phpize
./configure
make -j
make test
sudo make install

Enter fullscreen mode Exit fullscreen mode

PHP 8.3 minimum. No external library dependencies; yyjson is vendored in src/yyjson/.

The four-character migration

fastjson stays useful as long as yyjson's design choices (one-stage encoder, validate-only fast path, allocator hooks) beat what fits into ext/json's compatibility envelope. For the call sites where JSON serialization shows up on a flame graph, the migration is four characters; the rest of the codebase doesn't have to care.


Repo: https://github.com/iliaal/fastjson. Benchmark methodology and reproduction: bench/run.php. Visual baseline: https://iliaal.github.io/fastjson/baseline.html.