Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Run results for:
Perfomance: Switch (with functions) vs Polymorphism (with methods)
https://stackoverflow.com/questions/50401725/perfomance-switch-vs-polymorphism
Go to the benchmark
Embed
Embed Benchmark Result
Run details:
User agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0
Browser:
Chrome 134
Operating system:
Windows
Device Platform:
Desktop
Date tested:
one year ago
Test name
Executions per second
Polymorphism
4459813.0 Ops/sec
Switch
2767863.5 Ops/sec
Script Preparation code:
var class1 = { GetImportantValue: () => 1 }; var class2 = { GetImportantValue: () => 2 }; var class3 = { GetImportantValue: () => 3 }; var class4 = { GetImportantValue: () => 4 }; var class5 = { GetImportantValue: () => 5 }; function GetImportantValue1() { return 1; } function GetImportantValue2() { return 2; } function GetImportantValue3() { return 3; } function GetImportantValue4() { return 4; } function GetImportantValue5() { return 5; } getImportantValueSwitch = (myClassEnum) => { switch (myClassEnum.type) { case 'MyClass1': return GetImportantValue1(); case 'MyClass2': return GetImportantValue2(); case 'MyClass3': return GetImportantValue3(); case 'MyClass4': return GetImportantValue4(); case 'MyClass5': return GetImportantValue5(); } } getImportantValuePolymorphism = (myClass) => myClass.GetImportantValue();
Tests:
Polymorphism
getImportantValuePolymorphism(class1); getImportantValuePolymorphism(class2); getImportantValuePolymorphism(class3); getImportantValuePolymorphism(class4); getImportantValuePolymorphism(class5);
Switch
getImportantValueSwitch({type: 'MyClass1'}); getImportantValueSwitch({type: 'MyClass2'}); getImportantValueSwitch({type: 'MyClass3'}); getImportantValueSwitch({type: 'MyClass4'}); getImportantValueSwitch({type: 'MyClass5'});