Skip to content

Commit 05757aa

Browse files
authored
Merge pull request #10 from PivotPHP/v1.1.1
feat(json): Introduce JSON performance optimization with pooling mech…
2 parents 44eec0d + eb947ac commit 05757aa

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+5867
-78
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,4 @@ NOTES.md
260260
scratch/
261261
benchmarks/**/*.json
262262
CLAUDE.md
263+
proposals/

CHANGELOG.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,69 @@ All notable changes to the PivotPHP Framework will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [1.1.1] - 2025-07-10
9+
10+
### 🚀 **JSON Optimization Edition**
11+
12+
#### Added
13+
- **High-Performance JSON Buffer Pooling System**: Revolutionary JSON processing optimization
14+
- `JsonBuffer`: Optimized buffer class for JSON operations with automatic expansion
15+
- `JsonBufferPool`: Intelligent pooling system with buffer reuse and size categorization
16+
- **Automatic Integration**: `Response::json()` now uses pooling transparently for optimal performance
17+
- **Smart Detection**: Automatically activates pooling for arrays 10+ elements, objects 5+ properties, strings >1KB
18+
- **Graceful Fallback**: Small datasets use traditional `json_encode()` for best performance
19+
- **Public Constants**: All size estimation and threshold constants are now publicly accessible for advanced usage and testing
20+
21+
- **Performance Monitoring & Statistics**:
22+
- Real-time pool statistics with reuse rates and efficiency metrics
23+
- Configurable pool sizes and buffer categories (small: 1KB, medium: 4KB, large: 16KB, xlarge: 64KB)
24+
- Production-ready monitoring with `JsonBufferPool::getStatistics()`
25+
- Performance tracking for optimization and debugging
26+
27+
- **Developer Experience**:
28+
- **Zero Breaking Changes**: All existing code continues working without modification
29+
- **Transparent Optimization**: Automatic activation based on data characteristics
30+
- **Manual Control**: Direct pool access via `JsonBufferPool::encodeWithPool()` when needed
31+
- **Configuration API**: Production tuning via `JsonBufferPool::configure()`
32+
- **Enhanced Error Handling**: Precise validation messages separating type vs range errors
33+
- **Type Safety**: `encodeWithPool()` now always returns string, simplifying error handling
34+
35+
#### Performance Improvements
36+
- **Sustained Throughput**: 101,000+ JSON operations per second in continuous load tests
37+
- **Memory Efficiency**: 100% buffer reuse rate in high-frequency scenarios
38+
- **Reduced GC Pressure**: Significant reduction in garbage collection overhead
39+
- **Scalable Architecture**: Adaptive pool sizing based on usage patterns
40+
41+
#### Technical Details
42+
- **PSR-12 Compliant**: All new code follows project coding standards
43+
- **Comprehensive Testing**: 84 JSON tests with 329+ assertions covering all functionality
44+
- **Backward Compatible**: No changes required to existing applications
45+
- **Production Ready**: Tested with various data sizes and load patterns
46+
- **Centralized Constants**: All thresholds and size constants are unified to avoid duplication
47+
- **Test Maintainability**: Tests now use constants instead of hardcoded values for better maintainability
48+
49+
#### Files Added
50+
- `src/Json/Pool/JsonBuffer.php`: Core buffer implementation
51+
- `src/Json/Pool/JsonBufferPool.php`: Pool management system
52+
- `tests/Json/Pool/JsonBufferTest.php`: Comprehensive buffer tests
53+
- `tests/Json/Pool/JsonBufferPoolTest.php`: Pool functionality tests
54+
- `benchmarks/JsonPoolingBenchmark.php`: Performance validation tools
55+
56+
#### Files Modified
57+
- `src/Http/Response.php`: Integrated automatic pooling in `json()` method
58+
- Enhanced with smart detection and fallback mechanisms
59+
60+
#### Post-Release Improvements (July 2025)
61+
- **Enhanced Configuration Validation**: Separated type checking from range validation for more precise error messages
62+
- **Improved Type Safety**: `encodeWithPool()` method now has tightened return type (always returns string)
63+
- **Public Constants Exposure**: Made all size estimation and threshold constants public for advanced usage and testing
64+
- **Centralized Thresholds**: Unified pooling decision thresholds across Response.php and JsonBufferPool to eliminate duplication
65+
- **Test Maintainability**: Updated all tests to use constants instead of hardcoded values
66+
- **Documentation Updates**:
67+
- Added comprehensive [Constants Reference Guide](docs/technical/json/CONSTANTS_REFERENCE.md)
68+
- Updated performance guide with recent improvements
69+
- Enhanced error handling documentation
70+
871
## [1.1.0] - 2025-07-09
972

1073
### 🚀 **High-Performance Edition**

README.md

Lines changed: 97 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919
- **Arquitetura Moderna**: DI Container, Service Providers, Event System, Extension System e PSR-15.
2020
- **Segurança**: Middlewares robustos para CSRF, XSS, Rate Limiting, JWT, API Key e mais.
2121
- **Extensível**: Sistema de plugins, hooks, providers e integração PSR-14.
22-
- **Qualidade**: 315+ testes, PHPStan Level 9, PSR-12, cobertura completa.
23-
- **🆕 v1.0.1**: Suporte a validação avançada de rotas com regex e constraints.
24-
- **🚀 v1.0.1**: Suporte PSR-7 híbrido, lazy loading, object pooling e otimizações de performance.
22+
- **Qualidade**: 335+ testes, PHPStan Level 9, PSR-12, cobertura completa.
23+
- **🆕 v1.1.0**: High-Performance Edition com circuit breaker, load shedding e pooling avançado.
24+
- **🚀 v1.1.1**: JSON Optimization Edition com pooling automático e 101k+ ops/sec sustentados.
2525

2626
---
2727

@@ -37,7 +37,8 @@
3737
- 📚 **OpenAPI/Swagger**
3838
- 🔄 **PSR-7 Híbrido**
3939
- ♻️ **Object Pooling**
40-
-**Performance**
40+
- 🚀 **JSON Optimization** (v1.1.1)
41+
-**Performance Extrema**
4142
- 🧪 **Qualidade e Testes**
4243

4344
---
@@ -109,6 +110,53 @@ $app->get('/posts/:year<\d{4}>/:month<\d{2}>/:slug<slug>', function($req, $res)
109110
$app->run();
110111
```
111112

113+
### 🛣️ Sintaxes de Roteamento Suportadas
114+
115+
O PivotPHP suporta múltiplas sintaxes para definir handlers de rota:
116+
117+
```php
118+
// ✅ Closure/Função Anônima (Recomendado)
119+
$app->get('/users', function($req, $res) {
120+
return $res->json(['users' => []]);
121+
});
122+
123+
// ✅ Array Callable com classe
124+
$app->get('/users', [UserController::class, 'index']);
125+
126+
// ✅ Função nomeada
127+
function getUsersHandler($req, $res) {
128+
return $res->json(['users' => []]);
129+
}
130+
$app->get('/users', 'getUsersHandler');
131+
132+
// ❌ NÃO suportado - String no formato Controller@method
133+
// $app->get('/users', 'UserController@index'); // ERRO!
134+
```
135+
136+
**Exemplo com Controller:**
137+
138+
```php
139+
<?php
140+
141+
class UserController
142+
{
143+
public function index($req, $res)
144+
{
145+
return $res->json(['users' => User::all()]);
146+
}
147+
148+
public function show($req, $res)
149+
{
150+
$id = $req->param('id');
151+
return $res->json(['user' => User::find($id)]);
152+
}
153+
}
154+
155+
// Registrar rotas com array callable
156+
$app->get('/users', [UserController::class, 'index']);
157+
$app->get('/users/:id', [UserController::class, 'show']);
158+
```
159+
112160
### 🔄 Suporte PSR-7 Híbrido
113161

114162
O PivotPHP oferece **compatibilidade híbrida** com PSR-7, mantendo a facilidade da API Express.js enquanto implementa completamente as interfaces PSR-7:
@@ -151,6 +199,51 @@ $response = OptimizedHttpFactory::createResponse();
151199
-**API Express.js** mantida para produtividade
152200
-**Zero breaking changes** - código existente funciona sem alterações
153201

202+
### 🚀 JSON Optimization (v1.1.1)
203+
204+
O PivotPHP v1.1.1 introduz um sistema revolucionário de otimização JSON que melhora drasticamente a performance através de buffer pooling inteligente:
205+
206+
```php
207+
// Otimização automática - zero configuração necessária
208+
$app->get('/api/users', function($req, $res) {
209+
$users = User::all(); // 1000+ usuários
210+
211+
// Automaticamente usa pooling para datasets grandes
212+
return $res->json($users); // 101k+ ops/sec sustentados
213+
});
214+
215+
// Controle manual para casos específicos
216+
use PivotPHP\Core\Json\Pool\JsonBufferPool;
217+
218+
// Encoding direto com pooling
219+
$json = JsonBufferPool::encodeWithPool($largeData);
220+
221+
// Configuração para alta carga de produção
222+
JsonBufferPool::configure([
223+
'max_pool_size' => 500,
224+
'default_capacity' => 16384, // 16KB buffers
225+
'size_categories' => [
226+
'small' => 4096, // 4KB
227+
'medium' => 16384, // 16KB
228+
'large' => 65536, // 64KB
229+
'xlarge' => 262144 // 256KB
230+
]
231+
]);
232+
233+
// Monitoramento em tempo real
234+
$stats = JsonBufferPool::getStatistics();
235+
echo "Reuse rate: {$stats['reuse_rate']}%"; // Target: 80%+
236+
echo "Operations: {$stats['total_operations']}";
237+
```
238+
239+
**Características da Otimização JSON:**
240+
-**Detecção automática** - ativa pooling para arrays 10+ elementos, objetos 5+ propriedades
241+
-**Fallback inteligente** - dados pequenos usam `json_encode()` tradicional
242+
-**101k+ ops/sec** sustentados em testes de carga contínua
243+
-**100% reuso** de buffers em cenários de alta frequência
244+
-**Zero configuração** - funciona automaticamente com código existente
245+
-**Monitoramento integrado** - estatísticas detalhadas para otimização
246+
154247
### 📖 Documentação OpenAPI/Swagger
155248

156249
O PivotPHP inclui suporte integrado para geração automática de documentação OpenAPI:

VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.1.0
1+
1.1.1
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
require_once __DIR__ . '/../vendor/autoload.php';
6+
7+
use PivotPHP\Core\Json\Pool\JsonBuffer;
8+
use PivotPHP\Core\Json\Pool\JsonBufferPool;
9+
10+
/**
11+
* Benchmark to test JsonBuffer refactoring performance
12+
*/
13+
class JsonBufferRefactorBenchmark
14+
{
15+
public function run(): void
16+
{
17+
echo "🧪 JsonBuffer Refactoring Performance Test\n";
18+
echo "==========================================\n\n";
19+
20+
$iterations = 10000;
21+
$testData = [
22+
'message' => 'Hello, World!',
23+
'timestamp' => time(),
24+
'unicode' => '🚀 Performance Test',
25+
'url' => 'https://example.com/test',
26+
'nested' => [
27+
'level1' => ['level2' => ['level3' => 'deep value']],
28+
'array' => range(1, 50)
29+
]
30+
];
31+
32+
// Test 1: Direct JsonBuffer usage
33+
$start = microtime(true);
34+
for ($i = 0; $i < $iterations; $i++) {
35+
$buffer = new JsonBuffer();
36+
$buffer->appendJson($testData);
37+
$result = $buffer->finalize();
38+
}
39+
$directTime = microtime(true) - $start;
40+
41+
// Test 2: JsonBufferPool usage
42+
$start = microtime(true);
43+
for ($i = 0; $i < $iterations; $i++) {
44+
$result = JsonBufferPool::encodeWithPool($testData);
45+
}
46+
$poolTime = microtime(true) - $start;
47+
48+
// Test 3: Traditional json_encode
49+
$start = microtime(true);
50+
for ($i = 0; $i < $iterations; $i++) {
51+
$result = json_encode($testData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
52+
}
53+
$traditionalTime = microtime(true) - $start;
54+
55+
// Calculate performance metrics
56+
$directOps = $iterations / $directTime;
57+
$poolOps = $iterations / $poolTime;
58+
$traditionalOps = $iterations / $traditionalTime;
59+
60+
echo "📊 Results ({$iterations} iterations):\n";
61+
echo "Direct JsonBuffer: " . number_format($directOps, 0) . " ops/sec\n";
62+
echo "JsonBufferPool: " . number_format($poolOps, 0) . " ops/sec\n";
63+
echo "Traditional encode: " . number_format($traditionalOps, 0) . " ops/sec\n\n";
64+
65+
echo "⚡ Performance ratios:\n";
66+
echo "Buffer vs Traditional: " . number_format($directOps / $traditionalOps, 2) . "x\n";
67+
echo "Pool vs Traditional: " . number_format($poolOps / $traditionalOps, 2) . "x\n";
68+
echo "Pool vs Direct: " . number_format($poolOps / $directOps, 2) . "x\n\n";
69+
70+
// Test memory efficiency
71+
$memStart = memory_get_usage();
72+
73+
// Create and reuse buffers
74+
$buffer = new JsonBuffer();
75+
for ($i = 0; $i < 1000; $i++) {
76+
$buffer->appendJson($testData);
77+
$buffer->finalize();
78+
$buffer->reset();
79+
}
80+
81+
$memAfterReuse = memory_get_usage();
82+
$reuseMemory = $memAfterReuse - $memStart;
83+
84+
// Create new buffers each time
85+
$memStart = memory_get_usage();
86+
for ($i = 0; $i < 1000; $i++) {
87+
$buffer = new JsonBuffer();
88+
$buffer->appendJson($testData);
89+
$buffer->finalize();
90+
}
91+
$memAfterNew = memory_get_usage();
92+
$newMemory = $memAfterNew - $memStart;
93+
94+
echo "💾 Memory efficiency (1000 operations):\n";
95+
echo "Buffer reuse: " . number_format($reuseMemory / 1024, 2) . " KB\n";
96+
echo "New buffers: " . number_format($newMemory / 1024, 2) . " KB\n";
97+
echo "Memory saved: " . number_format(($newMemory - $reuseMemory) / 1024, 2) . " KB\n";
98+
echo "Efficiency: " . number_format((1 - $reuseMemory / $newMemory) * 100, 1) . "% less memory\n\n";
99+
100+
// Pool statistics
101+
echo "🏊 Pool Statistics:\n";
102+
$stats = JsonBufferPool::getStatistics();
103+
echo "Reuse rate: " . $stats['reuse_rate'] . "%\n";
104+
echo "Total ops: " . $stats['total_operations'] . "\n";
105+
echo "Current usage: " . $stats['current_usage'] . "\n";
106+
echo "Peak usage: " . $stats['peak_usage'] . "\n\n";
107+
108+
echo "✅ Refactoring Performance Test Complete!\n";
109+
}
110+
}
111+
112+
// Run the benchmark
113+
$benchmark = new JsonBufferRefactorBenchmark();
114+
$benchmark->run();

0 commit comments

Comments
 (0)