3v4l.org

run code in 500+ PHP versions simultaneously
<?php declare(strict_types=1); function totalRegistradosLenta(array $clientes, array $pedidos): array { $totales = []; foreach ($pedidos as $p) { if (in_array($p['rut'], array_column($clientes, 'rut'), true)) { $totales[$p['rut']] = ($totales[$p['rut']] ?? 0) + $p['monto']; } } return $totales; } function totalRegistradosRapida(array $clientes, array $pedidos): array { $registrados = array_flip(array_column($clientes, 'rut')); // una sola vez $totales = []; foreach ($pedidos as $p) { if (isset($registrados[$p['rut']])) { $totales[$p['rut']] = ($totales[$p['rut']] ?? 0) + $p['monto']; } } return $totales; } function verificar(string $caso, mixed $esperado, mixed $obtenido): void { printf("[%s] %s\n", $esperado === $obtenido ? ' OK ' : 'FALLA', $caso); } function generar(int $n): array { $clientes = $pedidos = []; for ($i = 1; $i <= $n; $i++) { $clientes[] = ['rut' => "{$i}-K", 'nombre' => "Cliente {$i}"]; $pedidos[] = ['rut' => rand(1, (int) ($n * 1.2)) . '-K', 'monto' => rand(500, 20000)]; } return [$clientes, $pedidos]; } [$c, $p] = generar(500); verificar('lenta y rápida dan lo mismo', totalRegistradosLenta($c, $p), totalRegistradosRapida($c, $p)); foreach ([1000, 2000, 4000] as $n) { [$c, $p] = generar($n); $t0 = hrtime(true); totalRegistradosLenta($c, $p); $t1 = hrtime(true); totalRegistradosRapida($c, $p); $t2 = hrtime(true); printf("n=%5d lenta: %8.2f ms rápida: %6.2f ms\n", $n, ($t1-$t0)/1e6, ($t2-$t1)/1e6); }

preferences:
23.87 ms | 480 KiB | 4 Q