var class1 = { GetImportantValue: () => 1 };
var class2 = { GetImportantValue: () => 2 };
var class3 = { GetImportantValue: () => 3 };
var class4 = { GetImportantValue: () => 4 };
var class5 = { GetImportantValue: () => 5 };
getImportantValueSwitch = (myClassEnum) => {
switch (myClassEnum.type) {
case 'MyClass1': return 1;
case 'MyClass2': return 2;
case 'MyClass3': return 3;
case 'MyClass4': return 4;
case 'MyClass5': return 5;
}
}
getImportantValuePolymorphism = (myClass) => myClass.GetImportantValue();
getImportantValuePolymorphism(class1);
getImportantValuePolymorphism(class2);
getImportantValuePolymorphism(class3);
getImportantValuePolymorphism(class4);
getImportantValuePolymorphism(class5);
getImportantValueSwitch({type: 'MyClass1'});
getImportantValueSwitch({type: 'MyClass2'});
getImportantValueSwitch({type: 'MyClass3'});
getImportantValueSwitch({type: 'MyClass4'});
getImportantValueSwitch({type: 'MyClass5'});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Polymorphism | |
Switch |
Test name | Executions per second |
---|---|
Polymorphism | 1360921984.0 Ops/sec |
Switch | 21414642.0 Ops/sec |
Let's dive into the explanation of the benchmark.
Benchmark Overview
The provided JSON represents a JavaScript performance benchmark that compares two approaches: switch statements and polymorphism (using method overriding). The goal is to determine which approach is faster for calling methods on different classes.
Switch Statement Approach
In this approach, the getImportantValue
function uses a switch statement to determine which value to return based on the type of the input object. This requires creating multiple cases for each possible input type (in this case, five types).
Pros and Cons:
Pros:
Cons:
Polymorphism Approach
In this approach, the getImportantValue
function calls a method named GetImportantValue
on the input object. This method is expected to be overridden in child classes.
Pros and Cons:
Pros:
Cons:
Library Used
In this benchmark, the class1
to class5
variables represent objects that are used as test subjects for both approaches. These classes do not extend any other class, which means they don't inherit from a base class with an overridden GetImportantValue
method.
Special JS Feature/ Syntax
None of the code snippets in this benchmark utilize any special JavaScript features or syntax, such as ES6 classes, async/await, or promises. However, it's worth noting that modern browsers and Node.js environments may still use some internal optimizations that might affect performance measurements.
Other Alternatives
Some alternative approaches to polymorphism could include:
It's also worth noting that the choice of approach often depends on the specific use case, performance requirements, and design constraints. This benchmark provides a controlled environment to compare two common alternatives in JavaScript programming.