Ok, so thanks to @Bergi and @VLAZ for their help with this. I ended up testing this code snippet in jsfiddle:
class MyClass {
constructor(data) {
this.UpdateClass(data);
}
UpdateClass(data) {
this.firstVar = this.GetFirstVar(data);
this.secondVar = this.GetSecondVar(data);
}
GetFirstVar(data) {
var first = data.slice(1, 4).join();
return first;
}
GetSecondVar(data) {
var cat = data.slice(2, 5);
return cat;
}
}
class MyClass2 {
constructor(data) {
this.firstVar = this.GetFirstVar(data);
this.secondVar = this.GetSecondVar(data);
}
UpdateClass(data) {
this.firstVar = this.GetFirstVar(data);
this.secondVar = this.GetSecondVar(data);
}
GetFirstVar(data) {
var first = data.slice(1, 4).join();
return first;
}
GetSecondVar(data) {
var cat = data.slice(2, 5);
return cat;
}
}
var testData = ['AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB'];
var case1= 0;
var case2= 0;
var caseup=0;
for(let y = 0; y < 10; y++){
var start = new Date().getTime();
for (let i = 0; i < 300000; i++) {
var testClass = new MyClass(testData);
}
var stop = new Date().getTime();
case1 += stop - start;
start = new Date().getTime();
for (let i = 0; i < 300000; i++) {
var testClass = new MyClass2(testData);
}
stop = new Date().getTime();
case2 += stop - start;
var testClass = new MyClass(testData);
start = new Date().getTime();
for (let i = 0; i < 300000; i++) {
testClass.UpdateClass(testData);
}
stop = new Date().getTime();
caseup += stop - start;
}
console.log(`Difference in first case is: ${case1 / 10} ms`)
console.log(`Difference in second case is: ${case2 / 10} ms`)
console.log(`Difference in update case is: ${caseup / 10} ms`)
Output (3m iterations):
Difference in first case is: 493.4 ms
Difference in second case is: 500.3 ms
Difference in update case is: 469.9 ms
So in this simplified version there does appear to be a performance difference for instantiating the class millions of time, but for values orders of magnitudes lower the performance difference becomes less apparent:
Output (300k iterations):
Difference in first case is: 49.6 ms
Difference in second case is: 49.1 ms
Difference in update case is: 47 ms
EDIT: I added the simple update case and rewrote the test to run ten times and take an average. Results should be more dependable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…