Switch Optimization

M

Mike and Jo

I've been converting some code to C++. I'm trying to use the Switch
function to compare a result. Is it possible to use switch to evaluate
'>0', '<0', 0?

Example

switch (result)
{
case (>0):
case (<0):
default:
}

I know this can be done in other languages but all the documentation I have
found in C++ show that you must evaluate const expressions (single values).
I am currently using and If - Else If - Else structure. Does anyone have an
efficient work around I can persue?

Thanx
Mike
 
G

Gianni Mariani

Mike said:
I've been converting some code to C++. I'm trying to use the Switch
function to compare a result. Is it possible to use switch to evaluate
'>0', '<0', 0?

Example

switch (result)
{
case (>0):
case (<0):
default:
}

I know this can be done in other languages but all the documentation I have
found in C++ show that you must evaluate const expressions (single values).
I am currently using and If - Else If - Else structure. Does anyone have an
efficient work around I can persue?

"if () {} else if () {} else {}" is pretty fast and likely faster than
or equal to "switch ( result == 0 ? ( result > 0 ? GT : LT ) : EQL )"

If you know the data you could make it so the first if succeeded most of
the time but even there, I've just spent more time typing this response
that you will likely ever save.
 
J

Jack Klein

I've been converting some code to C++. I'm trying to use the Switch
function to compare a result. Is it possible to use switch to evaluate
'>0', '<0', 0?
No.

Example

switch (result)
{
case (>0):
case (<0):
default:
}

I know this can be done in other languages but all the documentation I have
found in C++ show that you must evaluate const expressions (single values).
I am currently using and If - Else If - Else structure. Does anyone have an
efficient work around I can persue?

Thanx
Mike

The case labels in a switch statement must be compile-time constant
expressions that evaluate to an integer type value (meaning any
integer type, not just int).

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
 
M

Mike Wahler

Mike and Jo said:
I've been converting some code to C++. I'm trying to use the Switch
function to compare a result. Is it possible to use switch to evaluate
'>0', '<0', 0?

No. Also note that switch statements work the same
in C++ as in C.

'switch' is intended for use to compare a single
(variable) value against a set of known values.

Example

switch (result)
{
case (>0):
0 is not a value. result > 0 has a value
case (<0):

<0 is not a value.
result < 0 has a value.
default:
}

If you insist:

switch(result) {
case 0:
/* result == 0 */
break;
default:
/* result != 0 */
switch(result > 0) {
case 1:
/* result > 0 */
break;
default:
/* result < 0 */
break;
}
}
/* total of 15 lines */

But that's just silly. :)

if(result)
; /* result > 0 or < 0 */
else
if(result > 0)
; /* result > 0 */
else
; /* result == 0 */

/* total of 7 lines. */

Also, the words 'if' and 'else' are shorter to type
than 'switch', 'case n:', and 'default', don't you think? :)


I think you're wanting to use a tool for a task
for which it is not suited and for which a better one
already exists.
I know this can be done in other languages

IMO that's no reason to want to do it in C++
but all the documentation I have
found in C++ show that you must evaluate const expressions (single
values).

That's right.
I am currently using and If - Else If - Else structure. Does anyone have an
efficient work around I can persue?

What's wrong with if/else?

-Mike
 
D

David White

Mike and Jo said:
I've been converting some code to C++. I'm trying to use the Switch
function to compare a result. Is it possible to use switch to evaluate
'>0', '<0', 0?
No.

Example

switch (result)
{
case (>0):
case (<0):

The cases have to integral constants, not operations.
default:
}

I know this can be done in other languages but all the documentation I have
found in C++ show that you must evaluate const expressions (single values).
I am currently using and If - Else If - Else structure. Does anyone have an
efficient work around I can persue?

Your question implies that if/else is not efficient, but I don't see what's
wrong with it or how it could be improved upon.

DW
 
M

Mike and Jo

"Mike Wahler" Replied:

[snip]
If you insist:

switch(result) {
case 0:
/* result == 0 */
break;
default:
/* result != 0 */
switch(result > 0) {
case 1:
/* result > 0 */
break;
default:
/* result < 0 */
break;
}
}
/* total of 15 lines */

Thank you for your suggestion.

[snip]

IMO that's no reason to want to do it in C++

I was rather suprised when I translated a VB sort routine I use to C++ and
found the VB routine ran 3X as fast as the C++ routine. This portion (the
switch function) allows me to 'break' from the routine which is heavily used
in an indexing function. When this routine is constantly called hundreds of
throusands of times when comparing indexed arrays - that minute advantage
that the 'break' gives me really adds up.

Maybe the problem lies within the way I am accessing my arrays. I am not
very knowledgeable in C++.


Thank you for your response.
Mike
 
D

David B. Held

Mike and Jo said:
[...]
I was rather suprised when I translated a VB sort routine I
use to C++ and found the VB routine ran 3X as fast as the
C++ routine.
[...]

I'm surprised too! If you can, please post both the VB and
C++ code for the sort routine. There is probably a better
way to write your C++ version, and you might learn a few
new tricks in the process.

Dave
 
P

Peter van Merkerk

I've been converting some code to C++. I'm trying to use the Switch
function to compare a result. Is it possible to use switch to evaluate
'>0', '<0', 0?

Example

switch (result)
{
case (>0):
case (<0):
default:
}

I know this can be done in other languages but all the documentation I have
found in C++ show that you must evaluate const expressions (single values).
I am currently using and If - Else If - Else structure. Does anyone have an
efficient work around I can persue?

The reason that switch *may* (but not necessarilly does!) produce faster
code is that it is much more restricted than the if/else if/else
construct. If C++ would allow you to use switch the way you suggested,
there is no reason an optimizing compiler would produce faster code with
a switch statement than with the if/else if/else construct.

Are you sure that the if/else if/else is really the performance
bottleneck of your code, and if so how did you come to that conclusion?
 
M

Mike Wahler

David B. Held said:
Mike and Jo said:
[...]
I was rather suprised when I translated a VB sort routine I
use to C++ and found the VB routine ran 3X as fast as the
C++ routine.
[...]

I'm surprised too! If you can, please post both the VB and
C++ code for the sort routine.

Or try std::sort with the C++ code instead of the
hand rolled one.

-Mike
 
K

Karl Heinz Buchegger

Mike said:
I was rather suprised when I translated a VB sort routine I use to C++ and
found the VB routine ran 3X as fast as the C++ routine.

Did you write your own sort function?
C++ already has one general purpose sort functionality. For the average
programmer it is probably faster then anything they can write on their
own.
 
L

lilburne

Peter said:
Are you sure that the if/else if/else is really the performance
bottleneck of your code, and if so how did you come to that conclusion?

I suspect he has no such evidence. The compiler will convert
a most switches into an ifelse sequence anyway.
 
M

Mike and Jo

lilburne" said:
I suspect he has no such evidence. The compiler will convert
a most switches into an ifelse sequence anyway.

I was too quick in assuming the problem lies within the switch function. It
was the only difference I initially noticed between the two pieces of code.
Since the indexing function I use accesses the switch function 2.3 million
times in the process I run I thought that was the problem. As I stated
previously my I am not very knowledgable in C++.

After the replies I was given I wanted to see the actual gain in using
switch in the way I wanted. Being able to leave the comparison function
without comparing remaining expressions.

I timed a switch function compared with an if/elseif/else function. In C++
the if/elseIf/else out performed the the switch by a factor of 1.29 in my
particular scenario. (If clause 90 ms / switch clause 116 ms based on 10
million iterations in total. Used values 0,1,2 in the order if 0/else if 1/
else). This MAY not be the case if you have a large number of expressions
to compare in the switch function. I would place the most likely
expressions near the begining of the switch function in hope that the break
would let me leave the function early and not compare the switch against all
other expressions. I did not run timings on this so I do not know for sure
(stop assuming things - check).

The problem with my code obviously lies elsewhere - but I do know that the
if/elseif/else runs faster with my compiler than the switch.

Thank you for the responses
Mike
 
P

Peter van Merkerk

Are you sure that the if/else if/else is really the performance
conclusion?

I suspect he has no such evidence. The compiler will convert
a most switches into an ifelse sequence anyway.

I have seen compilers converting long switch/case statements to a jump
table indexed by the value of the switch condition. This saves a lot of
values comparisions. I can imagine that it would be more difficult (but
not impossible) for the compiler to make the same optimization with an
if/else if /else sequence.
 
P

Peter van Merkerk

I suspect he has no such evidence. The compiler will convert
I was too quick in assuming the problem lies within the switch function. It
was the only difference I initially noticed between the two pieces of code.
Since the indexing function I use accesses the switch function 2.3 million
times in the process I run I thought that was the problem. As I stated
previously my I am not very knowledgable in C++.

After the replies I was given I wanted to see the actual gain in using
switch in the way I wanted. Being able to leave the comparison function
without comparing remaining expressions.

I timed a switch function compared with an if/elseif/else function. In C++
the if/elseIf/else out performed the the switch by a factor of 1.29 in my
particular scenario. (If clause 90 ms / switch clause 116 ms based on 10
million iterations in total. Used values 0,1,2 in the order if 0/else if 1/
else). This MAY not be the case if you have a large number of expressions
to compare in the switch function. I would place the most likely
expressions near the begining of the switch function in hope that the break
would let me leave the function early and not compare the switch against all
other expressions. I did not run timings on this so I do not know for sure
(stop assuming things - check).

Depending on the optimization capabilities of your compiler and the
'case' values, reordering cases may or may not help.
The problem with my code obviously lies elsewhere - but I do know that the
if/elseif/else runs faster with my compiler than the switch.

Try to run your code through a profiler, this should pin-point in which
function the most time is spend. You could also post the relevant
(compilable) code here if it is not too long. People here may be able to
give you advice how to improve the performance of your code.
 
T

Thomas Matthews

Peter said:
I have seen compilers converting long switch/case statements to a jump
table indexed by the value of the switch condition. This saves a lot of
values comparisions. I can imagine that it would be more difficult (but
not impossible) for the compiler to make the same optimization with an
if/else if /else sequence.

One could create their own "jump table" by using either a
map<key, function pointer> or a table of such records.
But this depends on the selection criteria.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 
L

lilburne

Mike said:
After the replies I was given I wanted to see the actual gain in using
switch in the way I wanted. Being able to leave the comparison function
without comparing remaining expressions.

I timed a switch function compared with an if/elseif/else function. In C++
the if/elseIf/else out performed the the switch by a factor of 1.29 in my
particular scenario. (If clause 90 ms / switch clause 116 ms based on 10
million iterations in total. Used values 0,1,2 in the order if 0/else if 1/
else). This MAY not be the case if you have a large number of expressions
to compare in the switch function. I would place the most likely
expressions near the begining of the switch function in hope that the break
would let me leave the function early and not compare the switch against all
other expressions. I did not run timings on this so I do not know for sure
(stop assuming things - check).

As you have seen the difference between a switch and the
ifelse sequence is negligible: 26ms in 10,000,000
executions. Unless your application is time sensitive to the
extent that you need to count clock cycles micro
optimizations of this nature are a waste of time. Also your
descision today may well be invalidated by a compiler update.

Use which ever construct is the clearer in the specific
context. Some metrics consider that switch statements
increase complexity. But in certain circumstances the switch
conveys the programmers intent clearer than an ifelse.

If you have a large number of expressions to compare you are
probably better off reorganising the algorithm to reduce the
number of expressions that need to be tested.

Smarter algorithims and data structures will give far larger
performance boost than choice of programming construct.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top