di****@gmail.com wrote:
On Jul 17, 7:22 pm, Chris Dollin <e...@electrichedgehog.netwrote:
>They're all horrible, whatever their speed.
Lol... you put an smile with your expresion ;)
I'm serious that they're all horrible, if it's supposed to be
code that people read & write.
>(3) is the worst, since it falls foul of undefined behaviour:
you modify `p` /and/ independently read it. Don't do that.
I agree with you in all. I am trying to meassure the program to
see which one is faster. Even the one you suggested about using
a nice casting to an struct.
I did /not/ suggest any /casting/ to a struct. I suggested /using/
a struct.
I will comment the results.
>(1) and (2) are exactly equivalent in terms of C semantics,
since if `p` is a pointer and `i` is an int[eger] the
expression `p[i]` is defined to be/mean the same as `*(p+i)`.
yeah, but p[i] should be faster (in Intel) than *(p+i),
because p[i] is a machine instruction which can use preload,
while p + i needs from 2 instructions at least (all this
is assuming compiler does ZERO optimizations).
Compilers don't do ZERO optimisations nowadays. Turning the
code sequence for p, i, +, * into the same code sequence as
p, i, [] is the kind of thing that peephole optimisers could
do thirty years ago on 16-bit processors.
If you're interested in your code executing fast, you /will/ ask
the compiler to turn its optimisers on (up).
> 0.- p->base[p->offset]
My fear is that taking structs everywhere (just for a casting!)
There. Is. No. Casting. Here.
will make code even more terrible!. The expresions I wrote are
expanded inline, etc etc, which complex the tasks of looking
how they are translated in each use.
Ahhhh -- let me guess; this is supposed to be the compiled output
of something? `p` is a pointer into a fake machine store, hence
the type games? If so, then might be better off using a union:
typedef union machine_word Word;
union machine_word
{
Word *pointer;
int integer;
... other possibilities ...
};
...
Word *p;
...
p[0].pointer[p[1].integer]
But it depends. /Please/ tell us the context of the question:
it makes a difference. (In a compiler/interpreter I wrote
some time ago, I too had to play silly games moving between
types. I believe the games were justfied -- in context. But
they might not have been; several years later, I hope my
coding has continued to improve.)
>Unless, given the context, something even better suggested
itself.
Imagine it was an exam question ;)
Imagine the examiner having an epiphany and, instead of setting
the exam, taking a holiday in the Lake District.
Thanks for your answer, I appreciate it.
You're welcome.
--
Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England