Arrays

使用結構數組呼叫映射。優化還是性能推薦?

  • May 31, 2018

我有一個具有多個欄位和StudentInfo數組映射的結構。

struct StudentInfo {    
   uint studentId;
   uint courseId;
   uint age;
   string firstName; 
   string lastName; 
   string gender;         
   bool hasPassed;          
}

mapping(address => StudentInfo[]) public studentInfo;

基本上,老師可以檢索他/她的studentInfo.

可以通過以下函式將新的學生資訊保存到studentInfo狀態變數中:

function storeStudent(uint _studentId, uint _courseId, uint age, string _firstName, string _lastName, string gender) public returns (bool) {  
   studentInfo[msg.sender].push(StudentInfo(_studentId, _courseId, age, _firstName, _lastName, gender, 0));                
}

當老師需要檢索學生資訊列表時,我將其稱為如下:

function getStudentInfo(address _teacher) public view returns (uint[], uint[], uint[]) {
   uint length = studentInfo[_teacher].length;
   uint[] memory studentId = new uint[](length);
   uint[] memory courseId = new uint[](length);
   uint[] memory age = new uint[](length);   

   for (uint i = 0; i < length; i++) {
       studentId[i] = studentInfo[_teacher][i].studentId;
       courseId[i] = studentInfo[_teacher][i].courseId;
       age[i] = studentInfo[_teacher][i].age;
   }

   return (studentId, courseId, age);
}

function getStudentInfo2(address _teacher) public view returns (string[], string[], string[], bool[]) {
   uint length = studentInfo[_teacher].length;  
   string[] memory firstName = new string[](length);
   string[] memory lastName = new string[](length);
   string[] memory gender = new string[](length);
   bool[] memory hasPassed = new bool[](length);

   for (uint i = 0; i < length; i++) {     
       firstName [i] = studentInfo[_teacher][i].firstName ;
       lastName [i] = studentInfo[_teacher][i].lastName ;
       gender [i] = studentInfo[_teacher][i].gender ;
       hasPassed [i] = studentInfo[_teacher][i].hasPassed ;
   }

   return (firstName, lastName, gender, hasPassed);
}

這些功能正在工作,但我只是想知道如果尺寸studentInfo越來越大,是否會出現任何與性能或氣體(耗盡)相關的問題。

上面的邏輯可以優化嗎?

您可以通過使用結構映射而不是結構數組的映射來避免循環。

然後結構將包含每個參數的數組:

mapping(address => StudentInfo) public studentInfo;

struct StudentInfo {    
   uint[] studentId;
   uint[] courseId;
   uint[] age;
   string[] firstName; 
   string[] lastName; 
   string[] gender;         
   bool[] hasPassed;          
}

例如,您可以一次獲得所有名字:

studentInfo['teacherAddress'].fristName

其他參數相同

希望這可以幫助

引用自:https://ethereum.stackexchange.com/questions/50040