Improve performance for async functions
JulienLecoq opened this issue · comments
In some async functions, you're using redundant code that makes the execution code slower (I assume that this is also valid for the deno sdk). I didn't new at first that this redundant code could make the execution slower, but I tested it and here is my experience/results.
In some async functions, you're using the following pattern (from /lib/services/account.js):
async get() {
let path = '/account';
let payload = {};
return await this.client.call('get', path, {
'content-type': 'application/json',
}, payload);
}
This pattern contains an unnecessary "async" and "await" notation.
This could be simplified by:
get() {
let path = '/account';
let payload = {};
return this.client.call('get', path, {
'content-type': 'application/json',
}, payload);
}
From this pov, I decided to benchmark the 2 solutions with the following script:
async function measure_async_func(cb) {
const start = performance.now()
await cb()
const stop = performance.now()
const timeInSeconds = (stop - start) / 1000;
const timeRounded = timeInSeconds.toFixed(3)
return timeRounded
}
function printExecutionTime(funcName, executionTime) {
console.log(`Time taken to execute function ${funcName}(): ${executionTime} seconds`)
}
function getNumber() {
return new Promise((resolve, _) => {
resolve(10)
})
}
function getNumber1() {
return getNumber()
}
async function getNumber2() {
return await getNumber()
}
async function getNumbers1(numbersToGenerate) {
for (let i = 0; i < numbersToGenerate; i++) {
await getNumber1()
}
}
async function getNumbers2(numbersToGenerate) {
for (let i = 0; i < numbersToGenerate; i++) {
await getNumber2()
}
}
async function runTests() {
const numbersToGenerate = 10_000_000
const executionTime1 = await measure_async_func(() => getNumbers1(numbersToGenerate))
printExecutionTime("getNumbers1", executionTime1)
const executionTime2 = await measure_async_func(() => getNumbers2(numbersToGenerate))
printExecutionTime("getNumbers2", executionTime2)
const ratio = executionTime2 / executionTime1
console.log(`getNumbers1() is ${ratio} faster than getNumbers2()`)
}
runTests()
The results are (with Node v17.4.0):
Time taken to execute function getNumbers1(): 0.928 seconds
Time taken to execute function getNumbers2(): 1.613 seconds
getNumbers1() is 1.738146551724138 faster than getNumbers2()
I haven't tested with the sdk itself, but with a simple script, the second solution (without "async" and "await" notation) seems 1.74 times faster than the first one. I should have tested with the sdk itself, but I don't really have time for that rn.
i want to work on this issue , can you assign it to me.