better code

J

James Kanze

With static branch prediction, which label would usually be
predicted by a modern CPU? In
if( expression )
{ A: ... }
B: ...

if( expression )
{ A: ... }
else
{ B: ... }

It depends on which modern CPU. Some to rather poorly with
indirect branches (including returns from a function); others do
much better.
 
J

Jonathan Lee

That's illegal, and shouldn't compile.

Weird. I've been relying on "gcc -ansi -pedantic" too much, then.
Why?  The compiler is far more capable than you of counting the
exact frequencies.

The key word is "know". With regards to knowing, the compiler
is severely disadvantaged.
(Your example reminds me of Duff's device.  Or how to abuse
switch statments.)

I'm not suggesting anything of the sort. I'm not relying on fall
through, or jumping into the middle of switches. I'm saying that
if one behaviour happens 30,000,000 times more often than three
other behaviours combined, then it can make sense to put those
other three in an else block. So that there is only one condition
before getting to the most commonly executed code.

Yes, I do.
It would be necessary to examine the exact code you were
comparing, and then look at the generated code to be sure.  For
something like the above, I'd imagine that something like:

    switch ( x % 8 )
    {
    //  ...
    }

would be fastest.

That's what I imagined. I was wrong. At least with one
compiler, one platform, etc.

--Jonathan
 
J

Jonathan Lee

That's illegal, and shouldn't compile.  In general, the
semantics of a switch are those of a goto, and jumping over a
definition with an initializer is illega.

Comeau compiles it, too.

--Jonathan

switch(rand() % 8) {
unsigned x;
case 0: cout << '0' << endl; break;
case 1: cout << '1' << endl; break;
case 2:
x = rand();
cout << x << endl; break;
case 3: cout << '3' << endl; break;
case 4: cout << '4' << endl; break;
case 5: cout << '5' << endl; break;
case 6: cout << '6' << endl; break;
case 7: cout << '7' << endl; break;
default: cout << "Bleh" << endl;
}
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top