From 92958b49689a0a9e4c0e545eb218c1b7ed9c0b29 Mon Sep 17 00:00:00 2001 From: Jack Lee <280147597@qq.com> Date: Wed, 6 Nov 2024 16:07:00 +0700 Subject: [PATCH 1/2] add Using Assembly for Math Operations --- .../assemblyMathOperations.md | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md diff --git a/docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md b/docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md new file mode 100644 index 0000000000..683c0e1af2 --- /dev/null +++ b/docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md @@ -0,0 +1,132 @@ +--- +displayed_sidebar: generalSidebar +--- + +# Using Assembly for Math Operations + +When optimizing gas usage in Ethereum smart contracts, common mathematical operations can be made more efficient using assembly. While Solidity provides high-level math operations, using assembly implementations can lead to significant gas savings. + +### Standard vs Assembly Math Operations + +Here's a comparison showing both approaches: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract MathOperations { + // Standard implementation + function standardMax(uint256 x, uint256 y) public pure returns (uint256) { + return x > y ? x : y; + } + + // Assembly optimized implementation + function assemblyMax(uint256 x, uint256 y) public pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), gt(y, x))) + } + } + + // Standard implementation + function standardMin(uint256 x, uint256 y) public pure returns (uint256) { + return x < y ? x : y; + } + + // Assembly optimized implementation + function assemblyMin(uint256 x, uint256 y) public pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), lt(y, x))) + } + } +} +``` + +### Gas Comparison + +| Operation | Standard Implementation | Assembly Implementation | Potential Savings | +|-----------|------------------------|------------------------|------------------| +| Max | ~300 gas | ~200 gas | ~100 gas | +| Min | ~300 gas | ~200 gas | ~100 gas | + +### Common Assembly Math Operations + +1. **Maximum Value** +```solidity +function max(uint256 x, uint256 y) public pure returns (uint256 z) { + assembly { + z := xor(x, mul(xor(x, y), gt(y, x))) + } +} +``` + +2. **Minimum Value** +```solidity +function min(uint256 x, uint256 y) public pure returns (uint256 z) { + assembly { + z := xor(x, mul(xor(x, y), lt(y, x))) + } +} +``` + +3. **Average (with rounding up)** +```solidity +function average(uint256 x, uint256 y) public pure returns (uint256 z) { + assembly { + z := add(div(add(x, y), 2), and(and(x, y), 1)) + } +} +``` + +### Why Assembly is More Efficient + +1. **Fewer Operations**: Assembly implementations often use fewer EVM operations than their high-level counterparts. + +2. **No Conditional Jumps**: Assembly implementations can avoid conditional jumps (JUMPI operations) which are gas-intensive. + +3. **Direct Memory Access**: Assembly allows direct manipulation of values without additional overhead. + +### When to Use Assembly Math + +✅ **Recommended for:** + +- High-frequency mathematical operations +- Gas-critical contracts +- Simple mathematical functions +- When maximum efficiency is required + +❌ **Not recommended for:** + +- Complex mathematical operations +- When code readability is crucial +- When maintaining type safety is important +- Inexperienced developers + +### Best Practices + +1. **Documentation** + - Always comment assembly code thoroughly + - Explain the mathematical logic behind optimizations + +2. **Testing** + - Extensive testing across edge cases + - Comparison with standard implementations + - Gas measurement verification + +3. **Safety** + - Use `memory-safe-assembly` tag + - Verify overflow protection + - Consider using established libraries like Solady + +### Additional Resources + +For more optimized math operations, consider exploring: +- [Solady Library](https://github.com/Vectorized/solady) +- [PRBMath Library](https://github.com/PaulRBerg/prb-math) + +**Warning**: Assembly code bypasses Solidity's safety features. Ensure thorough testing and auditing before deployment. + +#### Gas Optimization Tips + +🌟 Consider using these assembly implementations for frequently called math operations in your smart contracts. Always benchmark your specific use case, as the effectiveness of optimizations can vary based on context and the Solidity compiler version. From b4eee87ff00d00ffff5560fe7dd60601416ea680 Mon Sep 17 00:00:00 2001 From: Jack Lee <280147597@qq.com> Date: Mon, 9 Dec 2024 22:23:14 +0800 Subject: [PATCH 2/2] update content --- .../assemblyMathOperations.md | 21 +++---------------- 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md b/docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md index 683c0e1af2..cdec8b0572 100644 --- a/docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md +++ b/docs/general/build/smart-contracts/gas-optimization/assemblyMathOperations.md @@ -12,7 +12,7 @@ Here's a comparison showing both approaches: ```solidity // SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; +pragma solidity ^0.8.24; contract MathOperations { // Standard implementation @@ -103,21 +103,6 @@ function average(uint256 x, uint256 y) public pure returns (uint256 z) { - When maintaining type safety is important - Inexperienced developers -### Best Practices - -1. **Documentation** - - Always comment assembly code thoroughly - - Explain the mathematical logic behind optimizations - -2. **Testing** - - Extensive testing across edge cases - - Comparison with standard implementations - - Gas measurement verification - -3. **Safety** - - Use `memory-safe-assembly` tag - - Verify overflow protection - - Consider using established libraries like Solady ### Additional Resources @@ -127,6 +112,6 @@ For more optimized math operations, consider exploring: **Warning**: Assembly code bypasses Solidity's safety features. Ensure thorough testing and auditing before deployment. -#### Gas Optimization Tips +#### Recommendations for gas optimization: -🌟 Consider using these assembly implementations for frequently called math operations in your smart contracts. Always benchmark your specific use case, as the effectiveness of optimizations can vary based on context and the Solidity compiler version. +🌟 Consider using these assembly implementations for frequently called math operations in your smart contracts.