Skip to content

Instantly share code, notes, and snippets.

@wschwab
Created June 22, 2022 16:40
Show Gist options
  • Save wschwab/f5ea7fd3fcfcca068877cd8d17e7a98e to your computer and use it in GitHub Desktop.
Save wschwab/f5ea7fd3fcfcca068877cd8d17e7a98e to your computer and use it in GitHub Desktop.
contract for testing if mapping key type affects gas cost (smaple tests included)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
/**
* INSTRUCTIONS:
* make sure you have a gas profiler set up
* you'll also need BitMaps from OpenZeppelin
* run a test/script that hits the functions and profiles gas
* there's a typescript file with Hardhat tests included
*/
import "@openzeppelin/contracts/utils/structs/BitMaps.sol";
contract MappingTester {
using BitMaps for BitMaps.BitMap;
mapping(uint256 => bool) public map;
mapping(address => bool) public addrMap;
BitMaps.BitMap private btmp;
constructor(address[] memory addrs) {
for (uint i = 0; i < 1000; i++) {
map[i] = true;
btmp.setTo(i, true);
addrMap[addrs[i]] = true;
}
}
function getFromMapping(uint256 index) external returns (bool) {
return map[index];
}
function getFromBitmap(uint256 index) external returns(bool) {
return btmp.get(index);
}
function getFromAddrMap(address addr) external returns(bool) {
return addrMap[addr];
}
}
import { expect } from "chai";
import { Contract } from "ethers";
import hre, { ethers } from "hardhat";
/**
* Make sure you have the Gas Profiler set up
* if you're using these tests
*/
describe("test mapping gas", () => {
let Tester: Contract;
let addrs: string[] = [];
beforeEach(async () => {
for (let i = 0; i < 1000; i++) {
const wllt = ethers.Wallet.createRandom();
const addr = await wllt.getAddress();
addrs.push(addr);
}
const artifact = await ethers.getContractFactory("MappingTester");
Tester = await artifact.deploy(addrs);
});
it("check gas for mapping and bitmap", async () => {
for (let i = 0; i < 2000; i++) {
await Tester.getFromMapping(i);
await Tester.getFromBitmap(i);
}
})
it("check gas for uint256 and address mapping", async () => {
for (let i = 0; i < 2000; i++) {
if(i > 1000) addrs.push(ethers.constants.AddressZero);
await Tester.getFromMapping(i);
await Tester.getFromAddrMap(addrs[i]);
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment