Which is faster in Spin- case statement or if statement? — Parallax Forums

# Which is faster in Spin- case statement or if statement?

Posts: 1,635

Title says it all...

• Posts: 17,761

No idea. But easy enough to test. Just read the cnt value, do a number of loops and read cnt again and subtract the first cnt.

• Posts: 4,901

In general I'd recommend writing the code to be clear for yourself and your readers. Use whatever construct (case or if) is more natural -- if you just have 2 choices, if/else is natural, if you have a lot more then case is probably more natural. If you're getting to the point where counting cycles to see whether case or if is faster, then you probably want to re-write that part of your code in PASM (or use flexspin to do that for you).

• Posts: 8,692

IIRC case is faster than if for more than two choices.

• Posts: 7,615

The great thing about using the Propeller is that you don't have to guess. I frequently do timing tests on bits of code like this:

```  t := cnt

' code to test

t := cnt - t - 368
term.dec(t)
```
• Posts: 1,718

@JonnyMac said:
The great thing about using the Propeller is that you don't have to guess. I frequently do timing tests on bits of code like this:

```  t := cnt

' code to test

t := cnt - t - 368
term.dec(t)
```

Yes, a great strength of the Propeller and spin. Even quite complex code like sorting a list of strings will (given the same input) always run at the same speed, down to the cycle.

• Posts: 1,635

@JonnyMac said:
The great thing about using the Propeller is that you don't have to guess. I frequently do timing tests on bits of code like this:

```  t := cnt

' code to test

t := cnt - t - 368
term.dec(t)
```

What is the reason for subtracting 368?

• Posts: 17,761

368 would be the number of clocks taken to so this test with nothing else (ie no if/case/etc) performed) within.

• Posts: 22,999
edited 2021-03-18 01:25

[deleted]

• Posts: 7,615

@"Don M" said:

@JonnyMac said:
The great thing about using the Propeller is that you don't have to guess. I frequently do timing tests on bits of code like this:

```  t := cnt

' code to test

t := cnt - t - 368
term.dec(t)
```

What is the reason for subtracting 368?

If you run that code as-is (hint, hint) the result will be 0, which is what we expect with no code between the checkpoints. As Ray pointed out, capturing of the timer and processing the result takes 368 system ticks (in this configuration); with that removed from the result, your tests will be accurate.

• Posts: 1,863

Wasn't there some form of jump-table being considered? I seem to remember Chip mentioning it, some time ago.

• Posts: 7,615

Not in the P1. In Spin2 there is a CASE_FAST structure that uses an internal jump table.

• Posts: 1,635

Thanks everyone.