473,406 Members | 2,343 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Swaping?

Hi,
Is there any way in C++ swap two values without using temp("third
variable").if yes thne how we can ?
Jan 12 '08 #1
41 1607
Andry wrote:
Hi,
Is there any way in C++ swap two values without using temp("third
variable").
Yes, but don't bother. It usually has no advantage over using a temporary
variable. The best is to use the std::swap function.

Jan 12 '08 #2
Andry <an*******@gmail.comwrote in news:4d464b6d-a112-4bb1-8b61-
2b**********@s8g2000prg.googlegroups.com:
Hi,
Is there any way in C++ swap two values without using temp("third
variable").if yes thne how we can ?

a ^= b;
b ^= a;
a ^= b;
--
Tomás Ó hÉilidhe
Jan 12 '08 #3
On 2008-01-12 13:14, Tomás Ó hÉilidhe wrote:
Andry <an*******@gmail.comwrote in news:4d464b6d-a112-4bb1-8b61-
2b**********@s8g2000prg.googlegroups.com:
>Hi,
Is there any way in C++ swap two values without using temp("third
variable").if yes thne how we can ?


a ^= b;
b ^= a;
a ^= b;
Nope, he said values, not just values of integer type, and the above
does not apply to values of user defined types.

--
Erik Wikström
Jan 12 '08 #4
Tomás Ó hÉilidhe wrote:
Andry <an*******@gmail.comwrote in news:4d464b6d-a112-4bb1-8b61-
2b**********@s8g2000prg.googlegroups.com:
>Hi,
Is there any way in C++ swap two values without using temp("third
variable").if yes thne how we can ?


a ^= b;
b ^= a;
a ^= b;
Just as a word of caution, this snippet fails to swap in this context:

int x = 5;
int& a = x;
int& b = x;

a ^= b;
b ^= a;
a ^= b;

In particular, it is not suitable for implementing a swap function for int.
Best

Kai-Uwe Bux
Jan 12 '08 #5
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?= <Er***********@telia.comwrote in
news:Qw*****************@newsb.telia.net:
>a ^= b;
b ^= a;
a ^= b;

Nope, he said values, not just values of integer type, and the above
does not apply to values of user defined types.

Wups, I should have realised I was in comp.lang.c++ rather than
comp.lang.c.

There's a "swap" function in C++ which is used for swapping objects.

--
Tomás Ó hÉilidhe
Jan 12 '08 #6
Tomás Ó hÉilidhe wrote:
Andry <an*******@gmail.comwrote in news:4d464b6d-a112-4bb1-8b61-
2b**********@s8g2000prg.googlegroups.com:
>Hi,
Is there any way in C++ swap two values without using temp("third
variable").if yes thne how we can ?


a ^= b;
b ^= a;
a ^= b;

Once again we are in the inane stupidity of premature optimization.

The C++ answer is yes, you use std::swap:

swap(a,b)

The computer answer in general, is that XOR is usually LESS
efficient than using a temporary. In many cases even
doing the XOR trick involves using temporary registers
on processors that can't XOR memory locations directly.
In which case the entire thing becomes subterfuge as

{
int t = a;
a = b;
b = t;
}

ends up not consuming any specific memory:

LD R1, a
LD R2, b
ST R1, b
ST R2, a

rather than

LD R1, a
LD R2, b
XOR R1,R1,R2
XOR R2,R2,R1
XOR R1,R1,R2
ST R1, a
ST R2, b
Further, once you get into classes rather than integers, swap
may be much more highly optimized than copying to a temporary
(and obviously most classes don't handle XOR).
Jan 12 '08 #7
Ron Natalie <ro*@spamcop.netwrote in news:4788b5f8$0$14066
$9*******@news.newshosting.com:
Once again we are in the inane stupidity of premature optimization.


There's nothing "prematuring optimising" about using one method over
another because it's more efficient.

I'm not saying that the XOR method is more efficient than the "temporary"
method, but if it were, it would make perfect sense to use it if you want
an efficient program.
--
Tomás Ó hÉilidhe
Jan 12 '08 #8
On 2008-01-12 15:31, Tomás Ó hÉilidhe wrote:
Ron Natalie <ro*@spamcop.netwrote in news:4788b5f8$0$14066
$9*******@news.newshosting.com:
>Once again we are in the inane stupidity of premature optimization.

There's nothing "prematuring optimising" about using one method over
another because it's more efficient.
In general no, if there are several ways to do something there is
nothing wrong with using the most efficient one, *unless* the most
efficient one also obscures the intent of the code. Code should be
written with clarity and correctness as primary goal, when you have
clear and correct working code you can, if necessary, start using less
obvious constructs to make it more efficient.

--
Erik Wikström
Jan 12 '08 #9
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?= <Er***********@telia.comwrote in
news:Sm*****************@newsb.telia.net:
In general no, if there are several ways to do something there is
nothing wrong with using the most efficient one, *unless* the most
efficient one also obscures the intent of the code. Code should be
written with clarity and correctness as primary goal, when you have
clear and correct working code you can, if necessary, start using less
obvious constructs to make it more efficient.

The language has comments for a reason. If the following is really too
obscure:

a ^= b;
b ^= a;
a ^= b;

, then replace it with:
a ^= b; /* Method for swapping */
b ^= a; /* the values of two */
a ^= b; /* integer types. */

If a programmer shies away from using code just because they can't
understand it at first glance, then I'd doubt the competentancy of that
programmer.

Of course there's business firms out there that have a policy of "the
dumber the better", but that doesn't mean the entire C++ developer
community should be watered down by it.

--
Tomás Ó hÉilidhe
Jan 12 '08 #10
On 2008-01-12 15:52, Tomás Ó hÉilidhe wrote:
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?= <Er***********@telia.comwrote in
news:Sm*****************@newsb.telia.net:
>In general no, if there are several ways to do something there is
nothing wrong with using the most efficient one, *unless* the most
efficient one also obscures the intent of the code. Code should be
written with clarity and correctness as primary goal, when you have
clear and correct working code you can, if necessary, start using less
obvious constructs to make it more efficient.


The language has comments for a reason. If the following is really too
obscure:

a ^= b;
b ^= a;
a ^= b;

, then replace it with:
a ^= b; /* Method for swapping */
b ^= a; /* the values of two */
a ^= b; /* integer types. */
It is not only other programmers that will read your code, the compiler
will also try to interpret what you want to do. In the old days when
compilers were not as good at optimising as they are today a number of
tricks were invented to make code faster. As Ron Natalie pointed out
using XOR might actually be slower because a compiler might not be smart
enough to figure out what the final results of XORing will be, but when
using a temporary the compiler can. Of couse, one should always measure
to be sure.

--
Erik Wikström
Jan 12 '08 #11
On 2008-01-12 09:52:41 -0500, "Tomás Ó hÉilidhe" <to*@lavabit.comsaid:
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?= <Er***********@telia.comwrote in
news:Sm*****************@newsb.telia.net:
>In general no, if there are several ways to do something there is
nothing wrong with using the most efficient one, *unless* the most
efficient one also obscures the intent of the code. Code should be
written with clarity and correctness as primary goal, when you have
clear and correct working code you can, if necessary, start using less
obvious constructs to make it more efficient.


The language has comments for a reason. If the following is really too
obscure:

a ^= b;
b ^= a;
a ^= b;

, then replace it with:
a ^= b; /* Method for swapping */
b ^= a; /* the values of two */
a ^= b; /* integer types. */
But the comment is wrong. First, the code doesn't swap the values of
two integer types, it swaps the values of two integers. Second, it
doesn't always swap the values of two integers, as has been pointed out
elsewhere. So the comment should probably be "Method for swapping the
values of two integers, or maybe setting them to zero".

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jan 12 '08 #12
On 2008-01-12 10:59:19 -0500, jk********@gmx.net said:
Tomás Ó hÉilidhe wrote:
>>
Of course there's business firms out there that have a policy of "the
dumber the better", but that doesn't mean the entire C++ developer
community should be watered down by it.

There seems to be an assumption here that

a ^= b;
b ^= a;
a ^= b;

is smarter than the "watered down" version

swap( a, b );

I wonder how you came to that conclusion.
Not smarter, but cleverer. Just like doing template metaprogramming to
fix edge cases that don't need to be fixed.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jan 12 '08 #13
Pete Becker <pe**@versatilecoding.comwrote in news:2008011210491216807-
pete@versatilecodingcom:
> a ^= b; /* Method for swapping */
b ^= a; /* the values of two */
a ^= b; /* integer types. */

But the comment is wrong. First, the code doesn't swap the values of
two integer types, it swaps the values of two integers. Second, it
doesn't always swap the values of two integers, as has been pointed out
elsewhere. So the comment should probably be "Method for swapping the
values of two integers, or maybe setting them to zero".

Do you find something ambiguous in "swap the values of two integer
types"? Were you under the mistaken belief that a type could have a value?
I can't think of any other meanings that can be taken from it (either
correct or otherwise).

--
Tomás Ó hÉilidhe
Jan 12 '08 #14
On Jan 12, 10:12 am, Andry <and.28...@gmail.comwrote:
Is there any way in C++ swap two values without using
temp("third variable").if yes thne how we can ?
None that work reliably.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 12 '08 #15
On Jan 12, 1:50 pm, "Tomás Ó hÉilidhe" <t...@lavabit.comwrote:
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?= <Erik-wikst...@telia.comwrote innews:Qw*****************@newsb.telia.net:
a ^= b;
b ^= a;
a ^= b;
Nope, he said values, not just values of integer type, and the above
does not apply to values of user defined types.
Wups, I should have realised I was in comp.lang.c++ rather than
comp.lang.c.
Even in comp.lang.c, it doesn't work. It fails for all non
integer types (e.g. floating point, pointers, structs...), and
it fails if a and b refer to the same object.
There's a "swap" function in C++ which is used for swapping
objects.
Which is generally the preferred method, because it will have
been specialized if there is some special way of swapping more
rapidly.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 12 '08 #16
On 2008-01-12 12:21:04 -0500, "Tomás Ó hÉilidhe" <to*@lavabit.comsaid:
Pete Becker <pe**@versatilecoding.comwrote in news:2008011210491216807-
pete@versatilecodingcom:
>>a ^= b; /* Method for swapping */
b ^= a; /* the values of two */
a ^= b; /* integer types. */

But the comment is wrong. First, the code doesn't swap the values of
two integer types, it swaps the values of two integers. Second, it
doesn't always swap the values of two integers, as has been pointed out
elsewhere. So the comment should probably be "Method for swapping the
values of two integers, or maybe setting them to zero".


Do you find something ambiguous in "swap the values of two integer
types"?
No. It's not ambiguous. It's simply wrong.
Were you under the mistaken belief that a type could have a value?
No.
I can't think of any other meanings that can be taken from it (either
correct or otherwise).
This isn't hard: you can't swap the values of types, so claiming that
that's what the code does is wrong.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jan 12 '08 #17
In article <Xn***************************@194.125.133.14>,
to*@lavabit.com says...

[ ... ]
I'd love to give a great example of cryptic-looking code that I'd
actually use... but I can't really think of any. I'd bitshift instead of
multiplying or dividing by a power of two... but that's not really
cryptic.
This depends (heavily) upon what you mean by "cryptic". Just for
example, consider changing:

if (x) y();

to:

x && y();

Is this cryptic or just strange? It does the same thing, and anybody who
knows C or C++ at all well should be able to figure out what it does
pretty easily, but I doubt anybody would claim it makes the code any
easier to read. Certainly few people code that way on a regular basis.
Are things considered cryptic if they're hidden away in a macro?
That depends. It's pretty typical that (especially in C) macros can be
written in a fashion that would otherwise be rather cryptic. For
example, if you want to put more than one statement in a macro, you
typically write it like:

do { statement1; statement2; } while (0);

In normal code that would be pointless and probably cryptic. In a macro,
it's widely recognized, though some frown upon it.
Is the following cryptic?

SWAP_INTS(a,b);
As it stands, no, it's fairly readable. OTOH, somebody might be likely
to wonder why you didn't just use std::swap.
The only thing I am against is the phobia of using efficient constructs
that are a little more complicated than their less efficient
counterparts. Of course, there are times I have gone for elegancy
instead of efficiency (especially when it comes to designing abstract
base classes as interfaces), but if I'm writing an algorithm then you
can be sure I won't be programming in the manner in which old women
drive.
I don't think there's any such phobia. There is, however, a perfectly
natural and well-founded dislike of using constructs that are odd for
the sake of being odd. Most code gains little or nothing from such
things as the XOR-based swap mentioned previously in this thread.

For most code that's really as efficient as its author can make it,
there's also something about 95% as efficient that's MUCH more readable.
The latter is _usually_ preferable.
Take an operating system like Windows XP... how much faster do you think
it would run if the programmers didn't go for the easiest solution every
time? Actually that's a bad example; Windows XP wouldn't run at all if
they went for the easist solution every time because Microsoft
programmers are mostly incompetant. But pretending for the moment that
they can program competantly, how much faster do you think it would run?
I'd say maybe 15% or 20% faster.
I think if you want to make such claims, you should back them up with
some sort of evidence -- and you should do so somewhere that such a post
is topical, of course. As it stands, your opinions appear to have little
basis in reality and marginal topicality (at best) to the newsgroup.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jan 12 '08 #18
Ron Natalie wrote:
Tomás Ó hÉilidhe wrote:
>Andry <an*******@gmail.comwrote in news:4d464b6d-a112-4bb1-8b61-
2b**********@s8g2000prg.googlegroups.com:
>>Hi,
Is there any way in C++ swap two values without using temp("third
variable").if yes thne how we can ?


a ^= b;
b ^= a;
a ^= b;

Once again we are in the inane stupidity of premature optimization.
No, it's probably homework. This pops up periodically.
Jan 12 '08 #19
Erik Wikström wrote:
On 2008-01-12 15:31, Tomás Ó hÉilidhe wrote:
>Ron Natalie <ro*@spamcop.netwrote in news:4788b5f8$0$14066
$9*******@news.newshosting.com:
>>Once again we are in the inane stupidity of premature optimization.
There's nothing "prematuring optimising" about using one method over
another because it's more efficient.

In general no, if there are several ways to do something there is
nothing wrong with using the most efficient one, *unless* the most
efficient one also obscures the intent of the code. Code should be
written with clarity and correctness as primary goal, when you have
clear and correct working code you can, if necessary, start using less
obvious constructs to make it more efficient.
And if the more efficient way isn't necessarily the more efficient
way in all cases. XOR is neither universally correct nor efficient.
Std::swap is correct and MOST LIKELY the most efficient.
The assumption that a limitted scope local variable causes inefficiency
is inane.
Jan 12 '08 #20
Pete Becker:

No. It's not ambiguous. It's simply wrong.
> Were you under the mistaken belief that a type could have a value?

No.
>I can't think of any other meanings that can be taken from it (either
correct or otherwise).

This isn't hard: you can't swap the values of types, so claiming that
that's what the code does is wrong.

I say "take the value of an integer type" instead of "take the value of
an integer type variable" in the same fashion that I say "give food to the
poor" rather than "give food to the poor people".

(Strictly speaking I should probably have a hyphen in it, i.e. "integer-
type", because I'm using it in similar fashion to an adjective).

I strip out redundancies, but of course there's no point debating it here.

--
Tomás Ó hÉilidhe
Jan 12 '08 #21
Jerry Coffin:
This depends (heavily) upon what you mean by "cryptic". Just for
example, consider changing:

if (x) y();

to:

x && y();

In reading the latter, I'd sort of presume that the author of the code
is trying to impress.

The "if" method is far more usual, but more importantly it was designed
exactly for this purpose.

>The only thing I am against is the phobia of using efficient
constructs that are a little more complicated than their less
efficient counterparts.

I don't think there's any such phobia. There is, however, a perfectly
natural and well-founded dislike of using constructs that are odd for
the sake of being odd. Most code gains little or nothing from such
things as the XOR-based swap mentioned previously in this thread.

I'm doing an embedded systems project in college at the moment. I
have to flash a display a good few times a second... and if my
algorithmic code is too slow then I won't get back around to re-flashing
the display quick enough. If an XOR swap would remedy this by virtue of
it being faster, then you can bet I'd use it.

>Take an operating system like Windows XP... how much faster do you
think it would run if the programmers didn't go for the easiest
solution every time? Actually that's a bad example; Windows XP
wouldn't run at all if they went for the easist solution every time
because Microsoft programmers are mostly incompetant. But pretending
for the moment that they can program competantly, how much faster do
you think it would run? I'd say maybe 15% or 20% faster.

I think if you want to make such claims, you should back them up with
some sort of evidence -- and you should do so somewhere that such a
post is topical, of course. As it stands, your opinions appear to have
little basis in reality and marginal topicality (at best) to the
newsgroup.

OK I see what you mean. Instead, I'll give approach specific methods:

* How many times do you think Windows uses dynamic memory allocation
when it could have used the stack?
* How many times does it peform redundant checks? (e.g. checking that a
parameter is valid before passing it to a function, and then checking it
again within the function).

In the case of Microsoft however, I woudn't suggest they remove the
redundant checks... but for competant programmers there's no need for
them to be there.

--
Tomás Ó hÉilidhe
Jan 12 '08 #22
Ron Natalie:
And if the more efficient way isn't necessarily the more efficient
way in all cases. XOR is neither universally correct nor efficient.
Std::swap is correct and MOST LIKELY the most efficient.
The assumption that a limitted scope local variable causes inefficiency
is inane.

You're exactly right in this case, std::swap should be magnificently fast.

Forgetting the XOR method for a moment tho, I was referring to the phobia
that people have of writing efficient code as they're writing it.

--
Tomás Ó hÉilidhe
Jan 12 '08 #23
On 2008-01-12 23:04, Tomás Ó hÉilidhe wrote:
Pete Becker:

>No. It's not ambiguous. It's simply wrong.
>> Were you under the mistaken belief that a type could have a value?

No.
>>I can't think of any other meanings that can be taken from it (either
correct or otherwise).

This isn't hard: you can't swap the values of types, so claiming that
that's what the code does is wrong.


I say "take the value of an integer type" instead of "take the value of
an integer type variable" in the same fashion that I say "give food to the
poor" rather than "give food to the poor people".

(Strictly speaking I should probably have a hyphen in it, i.e. "integer-
type", because I'm using it in similar fashion to an adjective).

I strip out redundancies, but of course there's no point debating it here.
If that is you goal you should say "take the value of an integer".

--
Erik Wikström
Jan 12 '08 #24
On 2008-01-12 23:13, Tomás Ó hÉilidhe wrote:
Jerry Coffin:
>This depends (heavily) upon what you mean by "cryptic". Just for
example, consider changing:

if (x) y();

to:

x && y();

In reading the latter, I'd sort of presume that the author of the code
is trying to impress.

The "if" method is far more usual, but more importantly it was designed
exactly for this purpose.
The same can be said about a lot of facilities that people try to find
clever alternatives for, such as std::swap().
>>The only thing I am against is the phobia of using efficient
constructs that are a little more complicated than their less
efficient counterparts.

I don't think there's any such phobia. There is, however, a perfectly
natural and well-founded dislike of using constructs that are odd for
the sake of being odd. Most code gains little or nothing from such
things as the XOR-based swap mentioned previously in this thread.

I'm doing an embedded systems project in college at the moment. I
have to flash a display a good few times a second... and if my
algorithmic code is too slow then I won't get back around to re-flashing
the display quick enough. If an XOR swap would remedy this by virtue of
it being faster, then you can bet I'd use it.
But you measured first to see that the swap was the part where you get
the most gain in optimising, right? There is nothing wrong with
optimisation, just premature optimisation. Why use a more complex (and
often more error-prone) construct unless it gives you a significant
speed-up in return? Unless you have been working with the same or
similar projects for some time and done a lot of measurements you
usually do not know shit about what needs to be optimised.
>>Take an operating system like Windows XP... how much faster do you
think it would run if the programmers didn't go for the easiest
solution every time? Actually that's a bad example; Windows XP
wouldn't run at all if they went for the easist solution every time
because Microsoft programmers are mostly incompetant. But pretending
for the moment that they can program competantly, how much faster do
you think it would run? I'd say maybe 15% or 20% faster.

I think if you want to make such claims, you should back them up with
some sort of evidence -- and you should do so somewhere that such a
post is topical, of course. As it stands, your opinions appear to have
little basis in reality and marginal topicality (at best) to the
newsgroup.

OK I see what you mean. Instead, I'll give approach specific methods:

* How many times do you think Windows uses dynamic memory allocation
when it could have used the stack?
What exactly do you mean with Windows in this case? And further more,
what investigations have you made that tells you that they are using the
stack more than they have to. We still would like some kind of evidence.

I am not a kernel hacker myself but I do know this, in kernel mode you
do not use the stack if you can help it, because the stack is usually tiny.
* How many times does it peform redundant checks? (e.g. checking that a
parameter is valid before passing it to a function, and then checking it
again within the function).
Examples? I have absolutely no idea about how many checks that they do,
but you seem to know.

--
Erik Wikström
Jan 12 '08 #25
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=:
There is nothing wrong with
optimisation, just premature optimisation.

I argue that there's no such thing as premature optimisation. While I'm
writing code, I'll think there and then "hmmm maybe I should do it this way
it'd be pretty fast".
Exactly do you mean with Windows in this case? And further more,
what investigations have you made that tells you that they are using
the stack more than they have to. We still would like some kind of
evidence.

If you use std::string's where you could have used char arrays on the
stack, then the code will be slower. Most times, the difference in speed
will not be noticable. However there was one time I wrote an algorithm to
convert "8732" to "Eight thousand, seven hundred and thirty-two" in three
different languages. I ran it against a database of fifty-hundred different
numbers, and the char array form was a hell of a lot faster than the
std::string form.

--
Tomás Ó hÉilidhe
Jan 12 '08 #26
On 2008-01-12 23:14, Tomás Ó hÉilidhe wrote:
Ron Natalie:
>And if the more efficient way isn't necessarily the more efficient
way in all cases. XOR is neither universally correct nor efficient.
Std::swap is correct and MOST LIKELY the most efficient.
The assumption that a limitted scope local variable causes inefficiency
is inane.


You're exactly right in this case, std::swap should be magnificently fast.

Forgetting the XOR method for a moment tho, I was referring to the phobia
that people have of writing efficient code as they're writing it.
One problem that software engineers face is the fact that unlike other
engineering professions we do not have as much hard facts about best
practices as they do, but one of those we do have is that premature
optimisation is the root of much evil. More efficient constructs are
often more error-prone, harder to understand, and less generic (which
makes future changes harder). And, unfortunately, all to often they do
not buy you very much efficiency, usually using clean code with a better
algorithm will give more noticeable differences.

Notice here that the important word is premature. Most of these
efficiency hacks are done without any prior measurements of what parts
of the program needs to improve, and often in parts where no noticeable
gain can be had.

Writing efficient code as they are writing it usually means that no
measurements have been done, and the optimisation is therefore usually
premature.

--
Erik Wikström
Jan 12 '08 #27
On 2008-01-12 23:49, Tomás Ó hÉilidhe wrote:
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=:
>There is nothing wrong with
optimisation, just premature optimisation.

I argue that there's no such thing as premature optimisation. While I'm
writing code, I'll think there and then "hmmm maybe I should do it this way
it'd be pretty fast".
And that piece of code will now be one hundred of a second faster and
will run once every hour, who will notice? Was the increased maintenance
cost worth it? Of course there are premature optimisation, if you work
in the industry for some time you are bound to come across it.
>Exactly do you mean with Windows in this case? And further more,
what investigations have you made that tells you that they are using
the stack more than they have to. We still would like some kind of
evidence.

If you use std::string's where you could have used char arrays on the
stack, then the code will be slower. Most times, the difference in speed
will not be noticable. However there was one time I wrote an algorithm to
convert "8732" to "Eight thousand, seven hundred and thirty-two" in three
different languages. I ran it against a database of fifty-hundred different
numbers, and the char array form was a hell of a lot faster than the
std::string form.
And what does that have to do with Windows code?

--
Erik Wikström
Jan 12 '08 #28
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=:
And that piece of code will now be one hundred of a second faster and
will run once every hour, who will notice? Was the increased
maintenance cost worth it? Of course there are premature optimisation,
if you work in the industry for some time you are bound to come across
it.

You're exactly right my friend.

But if it's run 50 thousand times in a loop per second, then you'll notice.
--
Tomás Ó hÉilidhe
Jan 13 '08 #29
Tomás Ó hÉilidhe wrote:
Ron Natalie:
>And if the more efficient way isn't necessarily the more efficient
way in all cases. XOR is neither universally correct nor efficient.
Std::swap is correct and MOST LIKELY the most efficient.
The assumption that a limitted scope local variable causes inefficiency
is inane.


You're exactly right in this case, std::swap should be magnificently fast.

Forgetting the XOR method for a moment tho, I was referring to the phobia
that people have of writing efficient code as they're writing it.
Who the hell said anything about phobia.
What I was railing about was people who have delusional ideas of what is
fast that flies in the face of over fifty years of software design.
I've been programming since 1975 and writing in C since 77. I've wrote
several compilers, and written portable code from everything from a
archaic microprocessor up to $25 million dollar supercomputers.
The problem is that people come up with economy of C lines of code
which have no freaking bearing to reality or if they can actually
measure some improvement in some tiny piece of the world, they can't
understand why it fails in the larger environment.
Jan 13 '08 #30
On 2008-01-12 17:04:37 -0500, "Tomás Ó hÉilidhe" <to*@lavabit.comsaid:
Pete Becker:

>No. It's not ambiguous. It's simply wrong.
>>Were you under the mistaken belief that a type could have a value?

No.
>>I can't think of any other meanings that can be taken from it (either
correct or otherwise).

This isn't hard: you can't swap the values of types, so claiming that
that's what the code does is wrong.


I say "take the value of an integer type" instead of "take the value of
an integer type variable" in the same fashion that I say "give food to the
poor" rather than "give food to the poor people".
plonk.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jan 13 '08 #31
On Jan 12, 6:08 pm, "Tomás Ó hÉilidhe" <t...@lavabit.comwrote:

[...]
I'd love to give a great example of cryptic-looking code that
I'd actually use... but I can't really think of any. I'd
bitshift instead of multiplying or dividing by a power of
two... but that's not really cryptic.
If the goal is to multiply or divide by a power of two, it's
obfuscation. It's the sort of thing amateurs love, but a
professional eschews. Also, of course, it's not even really
optimization---I've used machines where multiplication was
faster than shifting, and of course, today, the compiler will
choose whichever is faster.

(I've actually benchmarked 127 * x as opposed to (x << 7) - 1,
on a Sun Sparc, which doesn't---or didn't back then---have
hardward multiplication. The compiler converted the
multiplication into a shift and subtract, and managed to do so
with one less instruction than when I wrote it out explicitly,
doubtlessly because it knew the finality which was desired. I
did use something like ((a << 2) + a) << 1 to multiply by 10
once. But only after the profiler indicated a problem. With
conditional compilation so it didn't slow things down on our
other platform, which had fast multiplication. And of course,
modern compilers do this all by themselves---generally better
than the programmer can.)

The whole thread is becoming ridiculous. You're proposing
obfuscated code for presumed performance improvements, when 1)
the code doesn't actually work, 2) there is no indication that
performance is a problem to begin with, and 3) it's far from
sure that the obfuscated code will actually be faster. You
can't get much more amateurish.
Take an operating system like Windows XP... how much faster do
you think it would run if the programmers didn't go for the
easiest solution every time?
Have you actually seen the source code to Windows XP? Have you
benchmarked it to know where the speed is lost? Or are you just
spouting off about something you know nothing about.
Actually that's a bad example; Windows XP wouldn't run at all
if they went for the easist solution every time because
Microsoft programmers are mostly incompetant.
Do you actually know any Microsoft programmers. I've met
several, and all were very far from incompetent.
But pretending for the moment that they can program
competantly, how much faster do you think it would run? I'd
say maybe 15% or 20% faster.
I'd say that you don't know what you're talking about. Just a
guess, but I'd imagine that most of the performance in Windows
is used 1) protected the code from idiot users, and 2) making
things flashier---fancy visual effects can eat up enormous
amounts of CPU.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 13 '08 #32
On Jan 12, 11:49 pm, "Tomás Ó hÉilidhe" <t...@lavabit.comwrote:
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=:
There is nothing wrong with
optimisation, just premature optimisation.
I argue that there's no such thing as premature optimisation.
That's because you're an amateur, and not a professional. Me,
I'm paid to write code which fulfills the requirements
specifications and is easy to maintain, not to waste my time
(and the customer's money) on unnecessary optimizations which
aren't, and which render the code less maintainable.
While I'm writing code, I'll think there and then "hmmm maybe
I should do it this way it'd be pretty fast".
When I'm writing code, I'll thing there and then "hmmm maybe I
should do it this way---it'll be pretty easy to understand and
modify in the future."

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 13 '08 #33
James Kanze:
That's because you're an amateur, and not a professional. Me,
I'm paid to write code which fulfills the requirements
specifications and is easy to maintain, not to waste my time
(and the customer's money) on unnecessary optimizations which
aren't, and which render the code less maintainable.

Indeed your right. I'd hate to be a professional programmer. I program
just for the fun of it and I don't have to reshape the way I program to
satisfy customers and employers and the like.

Of course you make valid points when it comes to doing programming for
business reasons... but if someone's doing it for hobby then they'll be
doing it just exactly the way they want to.

--
Tomás Ó hÉilidhe
Jan 13 '08 #34
On Jan 13, 12:03 pm, "Tomás Ó hÉilidhe" <t...@lavabit.comwrote:
James Kanze:
That's because you're an amateur, and not a professional. Me,
I'm paid to write code which fulfills the requirements
specifications and is easy to maintain, not to waste my time
(and the customer's money) on unnecessary optimizations which
aren't, and which render the code less maintainable.
Indeed your right. I'd hate to be a professional programmer. I
program just for the fun of it and I don't have to reshape the
way I program to satisfy customers and employers and the like.
In that case, of course: if such analysis turns you on, then by
all means, do it. Just realize that that isn't the case for
most people programming in C++ (or just programming, for that
matter---but C++'s virtues really come to the fore in big
projects, which of course, an amateur can't do).
Of course you make valid points when it comes to doing
programming for business reasons... but if someone's doing it
for hobby then they'll be doing it just exactly the way they
want to.
Quite. It wouldn't be fun otherwise, would it?

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 13 '08 #35
James Kanze:
On Jan 13, 12:03 pm, "Tomás Ó hÉilidhe" <t...@lavabit.comwrote:
>James Kanze:

In that case, of course: if such analysis turns you on, then by
all means, do it. Just realize that that isn't the case for
most people programming in C++ (or just programming, for that
matter---but C++'s virtues really come to the fore in big
projects, which of course, an amateur can't do).

(Just to clarify before the discussion develops further: I use "amateur" in
contrast to "professional" to denote someone who doesn't get paid for what
they're doing. It's not any indication of the programmer's competance.)

I think you're overlooking the whole free software movement. Think Linux,
OpenOffice, Mozilla. Plenty of competant amateur programmers working on a
big project.

>Of course you make valid points when it comes to doing
programming for business reasons... but if someone's doing it
for hobby then they'll be doing it just exactly the way they
want to.

Quite. It wouldn't be fun otherwise, would it?

Nope.

--
Tomás Ó hÉilidhe
Jan 13 '08 #36
Tomás Ó hÉilidhe wrote:
James Kanze:
>On Jan 13, 12:03 pm, "Tomás Ó hÉilidhe" <t...@lavabit.comwrote:
>>James Kanze:

In that case, of course: if such analysis turns you on, then by
all means, do it. Just realize that that isn't the case for
most people programming in C++ (or just programming, for that
matter---but C++'s virtues really come to the fore in big
projects, which of course, an amateur can't do).


(Just to clarify before the discussion develops further: I use "amateur"
in contrast to "professional" to denote someone who doesn't get paid for
what they're doing. It's not any indication of the programmer's
competance.)

I think you're overlooking the whole free software movement. Think Linux,
OpenOffice, Mozilla. Plenty of competant amateur programmers working on a
big project.
Actually, the main difference is neither in getting paid nor in skill. The
important difference in the context of premature optimization and cryptic
coding is whether you are subject to some coding standard to facilitate
teamwork and maintainability. In none of the projects you listed, a
programmer would get away with cryptic code based on nothing more than
personal preference and a conjectured marginal performance gain.

Besides, I would venture the guess that James will not consider the projects
you mentioned as big :-)

Also: That the code is free doesn't imply that programmers don't get paid
for it. If I recall correctly, IBM has contributed code to Linux; and I bet
you the programmers didn't write it in their free time.

[snip]
Best

Kai-Uwe Bux
Jan 13 '08 #37
Actually that's a bad example; Windows XP wouldn't run at all if
they went for the easist solution every time because Microsoft
programmers are mostly incompetant.
Just for the record, I am pretty sure MS programmers are good - it is
the manangement and the cosntraints they work under that make for bad
products.

As for swapping, I am pretty sure std::swap makes use of type traits
to select the best swapping algorithm for the object in question.
Jan 14 '08 #38
In article <f9f8b4ff-16fe-4b95-98ab-0871eda02402
@e6g2000prf.googlegroups.com>, tr*****@gmail.com says...

[ ... ]
As for swapping, I am pretty sure std::swap makes use of type traits
to select the best swapping algorithm for the object in question.
Mostly it uses specialization to do the job. Quite a few things in the
standard library (e.g. containers) are required to provide
specializations of swap. You're also allowed to add a specialization of
swap to namespace std for your own types, when/if that makes sense.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jan 14 '08 #39
Jerry Coffin wrote:
In article <f9f8b4ff-16fe-4b95-98ab-0871eda02402
@e6g2000prf.googlegroups.com>, tr*****@gmail.com says...

[ ... ]
>As for swapping, I am pretty sure std::swap makes use of type traits
to select the best swapping algorithm for the object in question.

Mostly it uses specialization to do the job. Quite a few things in the
standard library (e.g. containers) are required to provide
specializations of swap.
Actually, those are overloads.
You're also allowed to add a specialization of
swap to namespace std for your own types, when/if that makes sense.
Unfortunately, the issue is a little more complicated (due to lack of
precision and foresight in the standard).

a) As you correctly point out, one is allowed to add _specializations_.
However, one is not allowed to add _overloads_ (at least formally the
standard does not give that license).

Consequently, the correct way to insert a custom swap for your own type
MyType into namespace standard looks suprisingly complicated:

namespace std {

template<>
void swap( MyType & lhs, MyType & rhs ) {
lhs.swap( rhs );
}

}
b) Adding insult to injury, it becomes therefore impossible to provide a
custom swap in namespace std for your own templates. If you do

namespace std {

template < typename T >
void swap ( MyTemplate<T& lhs, MyTemplate<T& rhs ) {
lhs.swap( rhs );
}

}

you are just adding overloads. The language does not (yet?) allow for
partial specializations of function templates.
c) When writing your own generic algorithms (which reside outside namespace
std), you have to decide whether to use

std::swap( a, b );

or

swap( a, b ); // use dependent name lookup to find the right swap.

It is unspecified which version the standard library uses, so there is no
clear lead to follow. (Maybe, it is good idea to do

namespace my_stuff {

using std::swap;

...

void some_function ( ... ) {
...
swap( a, b );
...
}

}

which would hopefully use std::swap unless dependent name lookup provides
the better match.)
d) The next version of the standard introduces the swappable concept. To be
swappable, the expression

swap( a, b )

is required to work. Then the algorithms in namespace std will use swap(a,b)
instead of std::swap(a,b) and putting the swap function into the same
namespace as the class / template (relying on dependent name lookup) seems
to be the RightThing(tm) with C++0X.
As of now, making sure that your custom swap will be found no matter what
can become quite a hassle.

Best

Kai-Uwe Bux
Jan 14 '08 #40
On Jan 13, 10:26 pm, jkherci...@gmx.net wrote:
Tomás Ó hÉilidhe wrote:
James Kanze:
On Jan 13, 12:03 pm, "Tomás Ó hÉilidhe" <t...@lavabit.comwrote:
James Kanze:
In that case, of course: if such analysis turns you on,
then by all means, do it. Just realize that that isn't the
case for most people programming in C++ (or just
programming, for that matter---but C++'s virtues really
come to the fore in big projects, which of course, an
amateur can't do).
(Just to clarify before the discussion develops further: I
use "amateur" in contrast to "professional" to denote
someone who doesn't get paid for what they're doing. It's
not any indication of the programmer's competance.)
I think you're overlooking the whole free software movement.
Think Linux, OpenOffice, Mozilla. Plenty of competant
amateur programmers working on a big project.
Actually, the main difference is neither in getting paid nor
in skill. The important difference in the context of premature
optimization and cryptic coding is whether you are subject to
some coding standard to facilitate teamwork and
maintainability. In none of the projects you listed, a
programmer would get away with cryptic code based on nothing
more than personal preference and a conjectured marginal
performance gain.
Perhaps not in those particular projects (although I don't
know---the only one I'm sure of is g++). But I could certainly
get away with it in my own library, and I don't.

In a certain way, you could argue that everyone is getting
paid---if not in money, then in some form of pleasure or
satisfaction. I've done the type of optimizations hÉilidhe
mentions in the past---I enjoy doing them. But I enjoy even
more the feeling I get from a job well done, or from people
admiring my code and finding it well written and maintainable,
or learning from it. When I code my library, I work for the
"greatest pleasure" (which is the greatest return on the
investment of my time). My greatest pleasure, but my greatest
pleasure comes from the viceral feeling of having produced
something of quality that is useful. So I forego the smaller
pleasure of tricky coding.

But that's me, and that's what turns me on.
Besides, I would venture the guess that James will not
consider the projects you mentioned as big :-)
It depends. Apache is certainly big---bigger than the servers I
work on, in fact. (Customizability creates size.)
Also: That the code is free doesn't imply that programmers
don't get paid for it. If I recall correctly, IBM has
contributed code to Linux; and I bet you the programmers
didn't write it in their free time.
And that those that did did so for the pleasure of creating a
quality product that people would use.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 14 '08 #41
Pete Becker wrote:
>The language has comments for a reason. If the following is really too
obscure:

a ^= b;
b ^= a;
a ^= b;

, then replace it with:
a ^= b; /* Method for swapping */
b ^= a; /* the values of two */
a ^= b; /* integer types. */

But the comment is wrong. First, the code doesn't swap the values of
two integer types, it swaps the values of two integers. Second, it
doesn't always swap the values of two integers,
It does.
as has been pointed out elsewhere.
If you are pedantic, you should also be consequent about it. What I see
pointed out is that if a and b are references to the very same integer, it
doesn't work. You can't use it to swap a single integer with itself.
Swapping two integers should work fine.

Jan 15 '08 #42

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: J. Campbell | last post by:
I have a class that contains an array of integers that hold the state of my 'system'. The system must be updated periodically. I need to update the whole system at once, at which point the system...
5
by: biju242 | last post by:
In my project i have a datagrid the values that are shown are taken from the database additional values can also be entere through a textbox on that form. i would like to add a dropdown list to that...
11
by: goal2007 | last post by:
I spent hours trying to find an example of onMouseOver and onMouseOut and OnClick. I did find somethings about onMouseOver and onMouseOut but not the onClick. can you please help me with an...
5
Ali Rizwan
by: Ali Rizwan | last post by:
I have two variables suppose a an b of integer type. Now i want to swap their values. Suppose if a =10 and b=5 then a=5 and b=10 But not want to declare another variable like temp=a a=b...
11
by: mukeshrasm | last post by:
Hi I want to swap the content of rows up or down based on the corresponding button clicked. <table border="0" width="200"> <tr> <td>first name </td><td>last name</td><td...
2
by: montakin | last post by:
I want to know details about swaping in c or c++ language and give me some example code on it....please..
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.