The optimizing compiler optimizes for what it’s seen. If it sees something new, that’s problematic.
Seleting properties has some strange implications on performacne.
We have seen that runing this code, interpertor can optimze js runtime:
const { performance } = require('perf_hooks');
let iterations = 1e7;
const a = 1;
const b = 2;
const add = (x, y) => x + y;
performance.mark('start');
while (iterations--) {
add(a, b);
}
performance.mark('end');
performance.measure('My Special Benchmark', 'start', 'end');
const [ measure ] = performance.getEntriesByName('My Special Benchmark');
console.log(measure);
So what if we do:
performance.mark("start");
while (iterations--) {
add(a, b);
}
add("foo", "bar"); // added this line
performance.mark("end");
So when we call add('foo', 'bar')
we see deoptimizing happens.
If we do:
performance.mark("start");
while (iterations--) {
add(a, b);
}
iterations = 1e7;
while (iterations--) {
add(a, b);
}
performance.mark("end");
We can see the result:
entryType: 'measure',
startTime: 41.05515700019896,
duration: 15.343078000470996,
If we add:
performance.mark("start");
while (iterations--) {
add(a, b);
}
add('foo', 'bar') // add this back
iterations = 1e7;
while (iterations--) {
add(a, b);
}
performance.mark("end");
Result:
entryType: 'measure',
startTime: 40.564633999951184,
duration: 32.49434900004417,
It doubles the runtime from 18ms to 32ms.
If we add:
performance.mark("start");
%NeverOptimizeFunction(add); // add this line
while (iterations--) {
add(a, b);
}
add("foo", "bar");
iterations = 1e7;
while (iterations--) {
add(a, b);
}
performance.mark("end");
Run: node --allow-natives-syntax benchmark.js
We can see the result:
entryType: 'measure',
startTime: 44.788716999813914,
duration: 143.67414100002497,
If we don't allow JS engine to optimize our code, then it would be pretty slow
标签:--,Javascript,while,mark,deoptimization,add,iterations,performance,Performance From: https://www.cnblogs.com/Answer1215/p/16949017.html