Warum sind Prototypenerweiterungen so viel langsamer als Funktionen?JavaScript

Javascript-Forum
Anonymous
 Warum sind Prototypenerweiterungen so viel langsamer als Funktionen?

Post by Anonymous »

Ich habe die Geschwindigkeit normaler JavaScript-Funktionen und Prototyp-Erweiterungen verglichen.

Code: Select all

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");


Ich habe festgestellt, dass das Gleiche in einer Erweiterung drei- bis viermal langsamer ist.

Code: Select all

As a function :  4.915 s
As a method   : 18.823 s
Warum ist das so? Können Sie es beschleunigen?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post