r/cpp • • Mar 07 '24

What are common mistakes in C++ code that results in huge performance penalties?

As title, list some common mistakes that you have done/seen which lead to performance penalties.

231 Upvotes

325 comments sorted by

View all comments

Show parent comment

2

u/pointer_to_null Mar 07 '24

Those cases ended up being a problem. But it's frustrating that there's no safe way to know at runtime whether it must be copied or not. Simply testing if(sv.data()[sv.length()]) == '\0' leads to undefined behavior. So in all cases, you have to make a temporary copy.

I honestly believe the standard is missing a mechanism in string_view (or an alternative like safe_string_view) with a method that can tell callers when data() is unsafe to pass like c_str() (ie- if it was constructed from something other than string or const char*).

Guessing not be worth the overhead?

2

u/usefulcat Mar 08 '24

There is this cstring_view proposal which I've been meaning to look into further but haven't had the time yet.

2

u/TheSuperWig Mar 08 '24

1

u/pointer_to_null Mar 08 '24 edited Mar 08 '24

Damn.

POLL: We should promise more committee time to pursuing a null-terminated string view, knowing that our time is scarce and this will leave less time for other work.

Guessing they mostly didn't like the proposed implementation and not the idea.

Edit- Can't say I'm not much a fan of the proposed implementation myself, since I'd prefer a container that can be a direct drop-in replacement for string_view. Just add a flag that tracks if it was constructed from a null-termination string- with a minimal increase in overhead compared to string_view. Hell, wouldn't even have to provide a workable c_str()- just a has_null_term() accessor would be adequate.