Optimize store_slice function to reduce gas consumption #1300
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Certainly! Here's a detailed explanation of the optimization process for the
store_slice
function in the TON Blockchain'sstdlib.fc
file:Overview:
The
store_slice
function within thestdlib.fc
file of the TON Blockchain has been identified as an area for potential optimization. The current implementation leads to unnecessary gas consumption due to the order of operations in the TON Virtual Machine (TVM). This document outlines the proposed changes, the expected benefits, and the steps to contribute this optimization back to the project.Current Issue:
The existing
store_slice
function is implemented as follows in C:This results in the following assembly instructions:
The gas consumption for this sequence is 44 units (18 for SWAP + 26 for STSLICER).
Proposed Optimization:
By rewriting the function directly in assembly, we can achieve the desired operation order without the need for an additional SWAP operation:
This change results in a more efficient single assembly instruction:
execute STSLICE
With this optimization, the gas consumption is reduced to just 18 units, which is a significant improvement over the original implementation.
Benefits of the Optimization:
Reduced Gas Consumption: The most immediate benefit is the reduction in gas consumption from 44 units to 18 units. This can lead to cost savings for users interacting with smart contracts on the TON Blockchain, as they will require less gas to execute the
store_slice
operation.Improved Efficiency: The optimized function is more efficient in terms of both gas usage and execution speed, as it eliminates the unnecessary SWAP operation.
Simplified Assembly: The assembly code is simplified, which can make it easier to understand and maintain.