Created
December 4, 2024 03:06
-
-
Save Mutefish0/67a3480af7e32e7a88b3da5a98da51fd to your computer and use it in GitHub Desktop.
Class vs Function_Entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 类模式 | |
class MyClass { | |
constructor(a, b) { | |
this.a = a; | |
this.b = b; | |
this.result = 0; | |
} | |
calculate() { | |
this.result = this.a + this.b; | |
} | |
} | |
// 数据+函数模式 | |
function createEntity(a, b) { | |
return { a, b, result: 0 }; | |
} | |
function calculate(entity) { | |
entity.result = entity.a + entity.b; | |
} | |
// 测试 | |
function benchmark() { | |
const instanceCount = 1_000_000; // 测试实例数量 | |
// 类模式 | |
console.time("Class Mode"); | |
const classInstances = []; | |
for (let i = 0; i < instanceCount; i++) { | |
classInstances.push(new MyClass(i, i)); | |
} | |
for (let instance of classInstances) { | |
instance.calculate(); | |
} | |
console.timeEnd("Class Mode"); | |
// 数据+函数模式 | |
console.time("Data + Function Mode"); | |
const dataEntities = []; | |
for (let i = 0; i < instanceCount; i++) { | |
dataEntities.push(createEntity(i, i)); | |
} | |
for (let entity of dataEntities) { | |
calculate(entity); | |
} | |
console.timeEnd("Data + Function Mode"); | |
} | |
// 运行基准测试 | |
benchmark(); | |
// Class Mode: 65.23388671875 ms | |
// Data + Function Mode: 34.880126953125 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment