Reputation: 550
To traverse an array would you shift left logical 2 times or would you increment the pointer to the base address each time by 4? What is the preferred method? What is the better method?
Upvotes: 1
Views: 3760
Reputation: 1076
Let's assume you're starting with $t0 pointing to the memory location at the start of your word array:
.data
mywords: .word 0:100 # 100 words, initialized to 0x0
.text
la $t0, mywords
Assuming you start with a value in $t0 that we don't want to shift, here are some alternatives:
sll method
# $t0 points to base address, $t1 word counter initialized to zero
loop:
sll $t2, $t1, 2 # Turn word pointer into a byte pointer
add $t2, $t0, $t2 # Get pointer to the word we want
lw $s0, 0($t2) # Load the word into $s0
addi $t1, $t1, 1 # Point to next word
# (do something useful here)
j loop
add method, preserving $t0
# $t0 points to base address, $t1 byte counter initialized to zero
loop:
add $t2, $t0, $t1 # Get pointer to the word we want
lw $s0, 0($t2) # Load the word into $s0
addi $t1, $t1, 4 # Point to next word
# (do something useful here)
j loop
add method, trashing $t0
# $t0 points to base address
loop:
lw $s0, 0($t0) # Load the word into $s0
addi $t0, $t0, 4 # Point to next word
# (do something useful here)
j loop
We were just discussing after class, which of these methods of building a loop is more efficient. I'd been doing the sll
method, because I like playing with bits... but it looks the least efficient of them all (by one instruction).
I guess it's going to depend on what variables you need to preserve.
sll method: $t0 tells you where you started, $t1 tells you which word you're on, $t2 is scratch
add method 1: $t0 tells you where you started, $t1 tells you which byte you're on, $t2 is scratch
add method 2: No idea where you are, but it frees up $t1 and $t2
Which one is "better" will, as usual, depend on your program's needs.
Upvotes: 2