Sign in to follow this  
gretty

When to use String Class Functions & when to use CString functions

Recommended Posts

Hello

I have a query about appending & comparing strings in c++. When I am, for example, trying to find whether a character exists in a string I could use .find() or I could convert the string to a cstring & use memchr().

I know that maybe the obvious answer is use string functions when you have a string & use cstring functions when you have a char array OR that string functions actually USE cstring functions so using either has the same result. But maybe converting a string to a cstring then using memchr() may actually turn out faster?

So when programming in c++ is it?...
- Better coding practice/standard to use string class functions
AND/OR
- Unsafe to use cstring functions because you are working directly with the memory & could make an error
AND/OR
- Faster to append & compare strings by going straight to cstring functions?

Share this post


Link to post
Share on other sites
Use the std::string unless you find a bottleneck.

If there is a bottleneck here, I suspect you might get more benefit by maintaining a searching data structure than just choosing between two reasonably similar algorithms.

In other words: Profile first, then macro-optimise, then micro-optimise (if necessary). Stop when profiling indicates performance is satisfactory or bottleneck is elsewhere.

Share this post


Link to post
Share on other sites
OR that string functions actually USE cstring functions so using either has the same result.

This. The expensive part of using std::string is the dynamic allocation. String comparison is more or less than same whether you're using c or c++. The real overhead of String is the dynamic allocation. It'll take over 100 times as long to allocate a String as it will to compare, say "Hello" and "World".

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this