Optimizing performance-critical sections of your WordPress PHP code is essential, especially when dealing with functions that are executed repeatedly or handle large datasets. Based on your provided function calcularPuntosPost, the primary bottleneck appears to be the time-related calculations and possibly the handling of meta data.
Below, I'll outline a series of optimizations tailored to your specific scenario, ensuring minimal precision loss while significantly enhancing performance.
1. Minimize Repeated Function Calls
Issue:
Functions like current_time('timestamp') and strtotime($post_date) are called within a loop or multiple times, leading to redundant computations.
Optimization:
-
Cache current_time('timestamp'):
Since current_time('timestamp') returns the same value throughout the execution of the script, you can retrieve it once and reuse it.
-
Precompute strtotime($post_date):
If $post_date follows a consistent format, consider storing it as a timestamp beforehand or ensure it's already in timestamp format when passed to the function.
Implementation:
function calcularPuntosPostOptimizado(
$post_id,
$post_data,
$datos,
$esAdmin,
$vistas_posts_processed,
$identifier = '',
$similar_to = null,
$current_timestamp = null // New parameter
) {
// Retrieve current timestamp once
if ($current_timestamp === null) {
$current_timestamp = current_time('timestamp');
}
$autor_id = $post_data->post_author;
$post_date = $post_data->post_date;
// If $post_date is not already a timestamp, convert it once
if (is_string($post_date)) {
$post_timestamp = strtotime($post_date);
} else {
$post_timestamp = $post_date; // Assume it's already a timestamp
}
// ... rest of the code ...
}
Usage:
When calling calcularPuntosPostOptimizado, pass the current_time('timestamp') once if you're processing multiple posts.
$current_timestamp = current_time('timestamp');
foreach ($posts as $post) {
calcularPuntosPostOptimizado(
$post->ID,
$post,
$datos,
$esAdmin,
$vistas_posts_processed,
'',
null,
$current_timestamp
);
}
2. Optimize Time Calculations
Issue:
Calculating the number of days since publication and then raising 0.99 to that power using pow can be computationally expensive, especially within loops.
Optimizations:
-
Use Integer Arithmetic:
If high precision isn't required, you can round or floor the number of days to reduce calculation variability.
-
Precompute Decay Factors:
Create a lookup table for pow(0.99, days) for a reasonable range of days (e.g., 0-365). This avoids recalculating the same power multiple times.
Implementation:
// Define a static lookup table for decay factors
function getDecayFactor($days) {
static $decay_factors = [];
// Populate the decay factors up to 365 days
if (empty($decay_factors)) {
for ($d = 0; $d <= 365; $d++) {
$decay_factors[$d] = pow(0.99, $d);
}
}
// Cap days to 365 to prevent undefined index
$days = min(max(0, (int) round($days)), 365);
return $decay_factors[$days];
}
Usage in calcularPuntosPostOptimizado:
$diasDesdePublicacion = ($current_timestamp - $post_timestamp) / (3600 * 24);
$diasDesdePublicacion = (int) floor($diasDesdePublicacion);
$factorTiempo = getDecayFactor($diasDesdePublicacion);
Benefits:
-
Reduced Function Calls:
Replacing pow with a simple array lookup drastically reduces computation time.
-
Integer Arithmetic:
Flooring the days and using integers make the decay factor retrieval faster and more predictable.
3. Simplify Meta Data Access
Issue:
Accessing nested arrays and objects repeatedly can be slow, especially if not properly checked or cached.
Optimizations:
Implementation:
// Access meta verificado and postAut results once
$verificado_result = isset($datos['verificado_results'][$post_id]->meta_value)
? $datos['verificado_results'][$post_id]->meta_value
: null;
$metaVerificado = ($verificado_result === '1');
$postAut_result = isset($datos['postAut_results'][$post_id]->meta_value)
? $datos['postAut_results'][$post_id]->meta_value
: null;
$metaPostAut = ($postAut_result === '1');
Benefits:
- Faster Access:
By minimizing isset and array lookups, you reduce the overhead associated with these operations.
4. Reduce Randomness Overhead
Issue:
Generating random numbers (mt_rand) can add overhead, especially if used multiple times within a loop.
Optimizations:
-
Limit Randomness:
If full randomness isn't essential, consider using a deterministic approach or reducing the range and frequency of random number generation.
-
Batch Randomness:
Generate random numbers in batches if possible.
Implementation:
// Generate randomness once and reuse or minimize usage
$aleatoriedad = mt_rand(0, 20);
$ajusteExtra = mt_rand(-50, 50);
Note:
Ensure that reducing randomness doesn't impact the functionality adversely. If randomness is crucial, this step might offer limited optimization.
5. Full Optimized Function
Combining all the above optimizations, here's the refactored calcularPuntosPostOptimizado function:
function calcularPuntosPostOptimizado(
$post_id,
$post_data,
$datos,
$esAdmin,
$vistas_posts_processed,
$identifier = '',
$similar_to = null,
$current_timestamp = null // New parameter
) {
// Retrieve current timestamp once
if ($current_timestamp === null) {
$current_timestamp = current_time('timestamp');
}
$autor_id = $post_data->post_author;
$post_date = $post_data->post_date;
// If $post_date is not already a timestamp, convert it once
if (is_string($post_date)) {
$post_timestamp = strtotime($post_date);
} else {
$post_timestamp = $post_date; // Assume it's already a timestamp
}
// Calculate days since publication
$diasDesdePublicacion = ($current_timestamp - $post_timestamp) / (3600 * 24);
$diasDesdePublicacion = (int) floor($diasDesdePublicacion);
$factorTiempo = getDecayFactor($diasDesdePublicacion); // Using the precomputed decay factor
// Calculate puntosUsuario
$puntosUsuario = in_array($autor_id, $datos['siguiendo']) ? 20 : 0;
// Calculate puntosIntereses
$puntosIntereses = calcularPuntosIntereses($post_id, $datos);
// Calculate puntosIdentifier
$puntosIdentifier = 0;
if (!empty($identifier) && isset($datos['post_content']) && isset($datos['datosAlgoritmo'])) {
$puntosIdentifier = calcularPuntosIdentifier($post_id, $identifier, $datos);
}
$pesoIdentifier = 1.0;
$puntosIdentifier *= $pesoIdentifier;
// Calculate puntosSimilarTo
$puntosSimilarTo = 0;
if (!empty($similar_to)) {
$puntosSimilarTo = calcularPuntosSimilarTo($post_id, $similar_to, $datos);
}
// Calculate puntosLikes
$likes = isset($datos['likes_by_post'][$post_id]) ? $datos['likes_by_post'][$post_id] : 0;
$puntosLikes = 30 + $likes;
// Access meta data efficiently
$verificado_result = isset($datos['verificado_results'][$post_id]->meta_value)
? $datos['verificado_results'][$post_id]->meta_value
: null;
$metaVerificado = ($verificado_result === '1');
$postAut_result = isset($datos['postAut_results'][$post_id]->meta_value)
? $datos['postAut_results'][$post_id]->meta_value
: null;
$metaPostAut = ($postAut_result === '1');
// Calculate puntosFinal
$puntosFinal = calcularPuntosFinales(
$puntosUsuario,
$puntosIntereses + $puntosSimilarTo,
$puntosLikes,
$metaVerificado,
$metaPostAut,
$esAdmin
);
$puntosFinal += $puntosIdentifier;
// Apply reduction based on views
if (isset($vistas_posts_processed[$post_id])) {
$vistas = $vistas_posts_processed[$post_id]['count'];
$reduccion_por_vista = 0.01;
$factorReduccion = pow(1 - $reduccion_por_vista, $vistas);
$puntosFinal *= $factorReduccion;
}
// Apply randomness and time factor
$aleatoriedad = mt_rand(0, 20);
$ajusteExtra = mt_rand(-50, 50);
$puntosFinal = ($puntosFinal * (1 + ($aleatoriedad / 100))) * $factorTiempo;
$puntosFinal += $ajusteExtra;
return max($puntosFinal, 0);
}
// Helper function for decay factors
function getDecayFactor($days) {
static $decay_factors = [];
// Populate the decay factors up to 365 days
if (empty($decay_factors)) {
for ($d = 0; $d <= 365; $d++) {
$decay_factors[$d] = pow(0.99, $d);
}
}
// Cap days to 365 to prevent undefined index
$days = min(max(0, (int) $days), 365);
return $decay_factors[$days];
}
6. Additional Recommendations
-
Profile Before and After:
Use profiling tools like Xdebug or Query Monitor to measure the performance gains of these optimizations.
-
Database Optimizations:
If meta data (verificado_results, postAut_results) is fetched from the database, ensure that queries are optimized, and consider using caching plugins or mechanisms like Transients API to store frequently accessed data.
-
Batch Processing:
If you're processing multiple posts, consider refactoring the function to handle batches of posts simultaneously, reducing overhead per post.
-
Use Object Caching:
Utilize WordPress's object caching to store and retrieve computed values that don't change frequently.
-
Avoid Unnecessary Calculations:
Ensure that all calculations are necessary for the final outcome. Remove or refactor any redundant computations.
-
Leverage PHP Opcache:
Ensure that PHP Opcache is enabled on your server to cache the compiled script bytecode, reducing script execution times.
-
Use Efficient Data Structures:
Ensure that $datos and other arrays are structured for optimal access patterns. For example, using associative arrays with keys matching $post_id can speed up access times.
Conclusion
By implementing these optimizations, you should observe a significant reduction in the execution time of the calcularPuntosPost function, especially in the sections related to time calculations and meta data access. Always remember to test each change incrementally to ensure that functionality remains intact and that performance gains are realized.
If further optimization is required, consider deeper profiling to identify other potential bottlenecks or refactoring the overall logic for enhanced efficiency.