As you know we can define a state variable using these 2 keywords: constant, immutable, or we don’t write anything about mutability.
address public ownerOne;
address public immutable ownerTwo;
address public constant ownerThree;
Let’s look at their differences:
constant
: If you use this keyword, you can’t change the state variable in the contract. You have to define the variable hard-coded.immutable
: If you use this keyword, you have to define the variable in the constructor. After than, you can’t change its value. As you can see it’s very similar to constant.- If you don’t specify anything, the mutability of the variable will be mutable. You can change its value wherever you want.
You can say “Why would I use constant or immutable”. Freedom has a price.
If you say “I don’t want to use them, I want to be free while I write the contract”, you’ll both fuck your user’s wallet and your wallet.
Here are the test results:
As you can see, there is a big difference in the deployment phase. You can save 51.517 gas by using constants than using mutable variables. You can check the contracts and the test file that I used here.
Give attention to contract call costs. Constant and immutable used the same amount of gas. So, using constant instead of immutable, saves money on your pocket, not from users’.
If you don’t use constant or immutable while you can, your users will pay nearly 5% more for every call!
Don’t screw your users.