Array Version: Pointer Version: Optimized Pointer Version: int strlen(char *str) { int strlen(char *str) { int strlen(char *str) { int length = 0; int length = 0; char *temp = str; while (str[length] != 0) { while (*str != 0) { while (*temp != 0) { length ++; str ++; temp ++; } length ++; } return length; } return (temp - str); } return length; } } strlen: strlen: strlen: li $v0, 0 li $v0, 0 move $v0, $a0 l: add $t0, $v0, $a0 l: lb $t0, 0($a0) l: lb $t0, 0($v0) lb $t0, 0($t0) beq $t0, $0, e beq $t0, $0, e beq $t0, $0, e add $a0, $a0, 1 add $v0, $v0, 1 add $v0, $v0, 1 add $v0, $v0, 1 j l j l j l e: sub $v0, $v0, $a0 e: jr $ra e: jr $ra jr $raWhen dealing with arrays of ints (or anything larger than bytes) the array index no longer equals the address offset, so we need an additional instruction to scale the array index, e.g.,
mul $t0, $v0, 4
add $t0, $t0, $a0
lw $t0, 0($t0)For non-byte arrays, the str ++ statement (or temp ++) has to add the size of the data item (instead of always 1) to the pointer. For example, the pointer increment for an array of integers would be:
add $v0, $v0, 4