Код: Выделить всё
function NormalizeSpace(str)
{
return str.trim().replace(/\s+/g, " ");
}
String.prototype.NormalizeSpace = function ()
{
return this.trim().replace(/\s+/g, " ");
};
function MeasureDuration(fun, label)
{
const t0 = performance.now();
for (let i = 0; i < 100000000; i++)
fun();
const t1 = performance.now();
const seconds = (t1 - t0) / 1000;
console.log(label.padEnd(13) + " : " + seconds.toFixed(3).padStart(6) + " s");
}
MeasureDuration(() => NormalizeSpace("abcd"), "As a function");
MeasureDuration(() => "abcd".NormalizeSpace(), "As a method");
Код: Выделить всё
As a function : 4.915 s
As a method : 18.823 s
Подробнее здесь: https://stackoverflow.com/questions/798 ... -functions
Мобильная версия