Swap macro

Started by
11 comments, last by farmersckn 23 years, 6 months ago
BTW, just thought I'd mention the performance of the two ways mentioned to swap variables:

void Func1(){	static int a = 1;	static int b = 2;		a^=b^=a^=b;}void Func2(){	static int a = 1;	static int b = 2;		int t = a;	a = b;	b = t;}   


Here's the time it took to run each function 100,000,000 times:
Function 1: 1.868420 seconds
Function 2: 1.264502 seconds

Not only is using a temporary value slightly faster, but it's also much easier to read.

- Houdini


Edited by - Houdini on October 8, 2000 10:07:25 PM
- Houdini
Advertisement
I have to say, I hadn''t expected so many replies so fast, thanks. And, it seems, I didn''t *need* them, because the method i was looking for works slower. I''d already thought of and written the template swap function, but i thought the macro would be faster. thanks for proving me wrong. otherwise, i would have lost that .6% speed increase...
farmersckn
Yesterday is the past, tomorrow is the future. Today is a gift, that is why we call it the present.
quote:
I''d already thought of and written the template swap function, but i thought the macro would be faster.


If you''re saying you thought the macro that involved the temp would be faster (not the XOR one), that''s not true. If you make the template function inline, then it would be the same speed. Templates only require extra work at compile time to be used. That is, there is no run time performance hit. All the templates do is to compile an instance of the function for every type that your code uses it with.

This topic is closed to new replies.

Advertisement