How can I make swap function faster in C ++?

I am writing a couple of string sorting algorithms using C ++, and I am wondering if I can make this swap operation faster.

void swap(string *items,int a, int b ){ string temp; temp = items[a]; items[a] = items[b]; items[b] = temp; } 

I would be grateful if you can help ...

+6
source share
4 answers

The String class has its own swap function.

 items[a].swap(items[b]); 

This is the fastest way to do this because it accesses the internal strings and avoids all copies.

See here .

+20
source

You can use std::swap() :

 void swap(string *items, int a, int b) { std::swap(items[a], items[b]); } 

But there is no guarantee that this will be noticeably faster, and this is probably not a slow part of your code. Have you measured the performance of a swap operation compared to the rest of your code?

+9
source

Use std::swap ; he will do his best. If your compiler supports C ++ 11 rvalue references, this means that it will take advantage of the move semantics to avoid copying that occurs in your swap function.

However, if your compiler does not support rvalue links, it will most likely work just like your swap function.

Most standard library implementations implement std::swap as something similar to:

 template<typename T> void swap(T& a, T& b) { T temp(std::move(a)); a = std::move(b); b = std::move(temp); } 

The std::move function will return a reference to rvalue (T & &) to the passed variable. When you try to assign this rvalue reference, it will invoke a type-move operator, if one is available. If the move operator is not available, it will run the copy operator, as usual.

In the case of std::string aforementioned swap function will not contain string copies from C ++ 11; only internal data will be copied, such as the length of the string and the C pointer. Without C ++ 11, it will make three copies of the actual contents of the string.

+6
source

You can change your algorithm to work with elements of type string* instead of string . Then all assignments in your swap function will work with pointers and will be faster because string copying will not be involved.

+4
source

Source: https://habr.com/ru/post/902323/


All Articles