I'm trying to write a function that counts the length of a string with the fewest number of dynamic instructions. This is what I have as of now:
strlen:
li $v0, 0 # len = 0
top:
lbu $t0, 0($a0) # get char
addi $v0, $v0, 1 # len++
addiu $a0, $a0, 1 # *s++
bne $t0, $0, top #if char != '\0', loop
ret:
addiu $v0, $v0, -1
jr $ra
I'm trying to reduce it with regards to a 10-character string so making it into a recursive function wouldn't be an "improvement". Is it possible to reduce the number of instructions from here at all?
You don't need to increment a counter in the loop, you can subtract end - start
to get the length. For example:
strlen:
addiu $v0, $a0, 1 # start + 1
top:
lbu $t0, 0($a0) # get char
addiu $a0, $a0, 1 # s++
bne $t0, $0, top # if char != '\0', loop
ret:
subu $v0, $a0, $v0 # (end+1) - (start+1)
jr $ra