2017-10-17 23 views
0

試想一下,我們有2的簡單類(略)口:Node.js的性能

class SomeService { 
    async func() { 
    // some async function logic 
    return value; 
    } 
} 

class SomeController { 
    constructor (service) { 
    this.service = service; 
    } 
    async func() { 
    const value = await this.service.func(); 
    // some controller-specific logic here 
    return value; 
    } 
} 

此外,我們得到了簡單的功能,即通過兩種方式使用此兩班。

案例一:

// require clasess 

const somefunc = async() => { 
    const controller = new SomeController(new SomeService()); 
    const value = await controller.func(); 
    return value; 
} 
module.exports = somefunc; 

案例二:

// require clasess 
const controller = new SomeController(new SomeService()); 

const somefunc = async() => { 
    const value = await controller.func(); 
    return value; 
} 
module.exports = somefunc; 

據我瞭解節點的require作品在第一種情況下controller會當每次somefunc被調用時被創建。在第二種情況下,只有一次創建controller,文件將被評估。什麼情況更好,更重要的是我應該閱讀或查找什麼來理解爲什麼?

+0

這不是關於「哪個更好」,而是「哪個範圍更好地模擬了你正試圖解決的問題」。 – aaaaaa

回答

0

我想答案取決於你的用例。每次調用或不調用函數時,都必須問自己是否需要重新創建SomeController。另一個要考慮的問題是SomeController在初始化時是否依賴某種異步。例如,如果控制器需要在其構造函數中訪問數據庫連接,則必須等待建立數據庫連接。在這種情況下,您可能別無選擇,只能在函數內初始化SomeController。正如我所說的,在這種情況下沒有客觀的better。這完全取決於你的用例。