Tengo una estructura que tiene varios campos y una asignación de StudentInfo
matriz.
struct StudentInfo {
uint studentId;
uint courseId;
uint age;
string firstName;
string lastName;
string gender;
bool hasPassed;
}
mapping(address => StudentInfo[]) public studentInfo;
Básicamente, un maestro puede recuperar su lista de archivos studentInfo
.
Se puede guardar una nueva información de estudiante en studentInfo
la variable de estado a través de la siguiente función:
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));
}
y cuando el maestro necesita recuperar la lista de StudentInfo, lo llamo como se muestra a continuación:
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);
}
Esas funciones están funcionando, pero me pregunto si podría haber algún problema relacionado con el rendimiento o el gas (se agota) si el tamaño se studentInfo
hace cada vez más grande.
¿Se pueden optimizar las lógicas anteriores?
Puede evitar el bucle si tiene una asignación de estructura en lugar de una asignación de matrices de estructuras.
Luego, la estructura contendrá matrices para cada parámetro:
mapping(address => StudentInfo) public studentInfo;
struct StudentInfo {
uint[] studentId;
uint[] courseId;
uint[] age;
string[] firstName;
string[] lastName;
string[] gender;
bool[] hasPassed;
}
Puede obtener, por ejemplo, todos los nombres de una sola vez haciendo:
studentInfo['teacherAddress'].fristName
Lo mismo para los demás parámetros.
Espero que esto ayude