perf: pickup free worker in the less busy and used strategies for fixed
[poolifier.git] / src / pools / selection-strategies / less-busy-worker-choice-strategy.ts
1 import type { IPoolWorker } from '../pool-worker'
2 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
3 import type { RequiredStatistics } from './selection-strategies-types'
4
5 /**
6 * Selects the less busy worker.
7 *
8 * @typeParam Worker - Type of worker which manages the strategy.
9 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
10 * @typeParam Response - Type of response of execution. This can only be serializable data.
11 */
12 export class LessBusyWorkerChoiceStrategy<
13 Worker extends IPoolWorker,
14 Data,
15 Response
16 > extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
17 /** {@inheritDoc} */
18 public readonly requiredStatistics: RequiredStatistics = {
19 runTime: true
20 }
21
22 /** {@inheritDoc} */
23 public reset (): boolean {
24 return true
25 }
26
27 /** {@inheritDoc} */
28 public choose (): number {
29 const freeWorkerKey = this.pool.findFreeWorkerKey()
30 if (!this.isDynamicPool && freeWorkerKey !== false) {
31 return freeWorkerKey
32 }
33 let minRunTime = Infinity
34 let lessBusyWorkerKey!: number
35 for (const [index, workerItem] of this.pool.workers.entries()) {
36 const workerRunTime = workerItem.tasksUsage.runTime
37 if (workerRunTime === 0) {
38 return index
39 } else if (workerRunTime < minRunTime) {
40 minRunTime = workerRunTime
41 lessBusyWorkerKey = index
42 }
43 }
44 return lessBusyWorkerKey
45 }
46
47 /** {@inheritDoc} */
48 public remove (workerKey: number): boolean {
49 return true
50 }
51 }