1

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?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
user2871354
  • 530
  • 1
  • 5
  • 15

1 Answers1

2

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.

RobertB
  • 946
  • 1
  • 9
  • 22
  • The pointer-increment one is clearly better; if you need the original `$t0` later, copy it once outside the loop, instead of wasting instructions inside. All of these loops are infinite; normally you'd use `bne $t0, $t1, loop` instead of `j loop`, with `$t1` being a pointer to one-past-the-end which you calculated earlier, outside the loop. Like in [Translating C function with args to MIPS: loop over an int array and count negatives](https://stackoverflow.com/a/49518837) – Peter Cordes Mar 27 '21 at 13:39