solidity – Comparing Speed Differences Between Solidity and JavaScript

solidity

Suppose I have a solidty smart contract that calls getReserves of a certain pair say weth/token. Now my goal is to sum these two reserves, reserveWeth + reserveToken. Would it be faster to execute this computation on the solidity smart contract directly after fetching the reserves or instead, to await for the return value of calling the smart contract to get reserves and then performing this operation on my computer using a javascript file.

Basically what is faster

option1

const reserves = await fetchingData.getReserves(weth,token) //runs on javascript file
//this will call the contract fetchingData
contract fetchingData {
function getReserves(weth,token){
const reserves = getReserves(weth, token)
const sum = reserves[0] + reserve[1]
return sum
}
//this returns the sum to my javascript file
}

option2

const reserves = await fetchingData.getReserves(weth,token) //runs on javascript
//this will call the contract fetchingData
contract fetchingData {
function getReserves(weth,token){
const reserves = getReserves(weth, token)
return reserves
}
//this returns the reserves (not the sum) to my javascript file
}
//on my javascript file, using the return value I sum them
const sum = reserves[0] + [1];

now consider this over a large computation operation, certainly there will be a speed difference. Which is faster ?
Also when you call a smart contract's code where does it execute?

Best Answer

Solidity is not designed to be very efficient in almost any way. Also the EVM is not designed to be efficient speed-wise. The EVM is probably one of the worst 'computers' there is for speed.

If you are only issuing read-only queries to a contract, it will be for free anyway since the call only reaches the node you're connected to. But it won't be fast: any EVM operations (even just reads) are slow. But if already know that you need your own contract, you could just include the calculations there as well - getting the data will be slow no matter what the contract does, so it doesn't make much difference whether the contract does an extra calculation.

But in any case JavaScript should be a lot faster and better than the EVM. If there's no need to keep the calculation in the EVM (maybe there is for trust reasons or integrations with other contracts?) you shouldn't keep it there.

Related Topic