Skip to content

Instantly share code, notes, and snippets.

@SamWSoftware
Created October 26, 2023 16:30
Show Gist options
  • Save SamWSoftware/c1547de574a68f1dc9cad4036e146907 to your computer and use it in GitHub Desktop.
Save SamWSoftware/c1547de574a68f1dc9cad4036e146907 to your computer and use it in GitHub Desktop.
better performance test
export const handler = async (event) => {
// TODO implement
//#Source https://bit.ly/2neWfJ2
const hz = (fn, iterations = 100) => {
const before = performance.now();
for (let i = 0; i < iterations; i++) fn();
return (1000 * iterations) / (performance.now() - before);
};
// 10,000 element array
const numbers = Array(10000)
.fill()
.map((_, i) => i);
// Test functions with the same goal: sum up the elements in the array
const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);
const sumForLoop = () => {
let sum = 0;
for (let i = 0; i < numbers.length; i++) sum += numbers[i];
return sum;
};
function getStandardDeviation (array) {
const n = array.length
const mean = array.reduce((a, b) => a + b) / n
return Math.sqrt(array.map(x => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n)
}
const getStats = (fn, iterations = 100) => {
const data = [];
for (let i = 0; i < iterations; i++) {
data.push(Math.round(hz(fn)))
};
return {
min: Math.min(...data),
max: Math.max(...data),
average: data.reduce((partialSum, a) => partialSum + a, 0)/data.length,
stDev: getStandardDeviation(data),
}
}
// sumForLoop` is nearly 10 times faster
const statsReduce = getStats(sumReduce);
const statsForLoop = getStats(sumForLoop);
const response = {
statusCode: 200,
body: JSON.stringify({
memory: process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE,
statsReduce,
statsForLoop
}),
};
return response;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment