Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance advantages of const qualifier in C11

The advantages of the 'const' qualifier have been discussed in various questions, but these discussions relate mostly to failsafes against unintentional modification and clarity of intent. I would like to ask if there is any difference in the resulting program due to the use of the qualifier- in particular, is there a performance gain?

In one of the other questions it was noted that the compiler could not use the natural assumption of an object not changing if passed to a function with the const qualifier given the existence in C++ of 'const_cast'. That is not in C11, so does const allow any optimizations in C11 that would be missed without it?

Another possibility for performance differences is in the memory layout in the case of static objects. Is there any performance advantage to having an object in read only space? This may be hardware dependent, I'd be interested in both general insights and comments specific to particular configurations.

EDIT: It would be a very broad request to ask for a general argument asserting that there cannot be a performance gain making necessary use of 'const'. However, a negation of this assertion would probably be a fairly concise response. So, to be more particular, and without excluding anything addressing my general question, answer forms that would be particularly helpful are as follows:

  1. Any example of a case where a performance gain is achieved using 'const' in a necessary way.

  2. Any argument as to why the compiler can't make an optimization because of the use of 'const'. This would probably not be hardware specific, and so if this is the case, it probably can be given concisely. If this needs to be more specific, I am most interested in the use of 'const' in function calls.

  3. Any answer as to whether read only memory can be used with static objects to achieve a performance gain in desktop or server implementations of x86-64.

This being said, I would appreciate the most general answer to the question as initially stated as is reasonable to provide.

like image 965
jack Avatar asked Apr 21 '15 03:04

jack


1 Answers

I guess that in principle, a compiler could optimize more when code has a lot of const qualifier.

I imagine that with the following code:

 extern void foo(const int*const);

 int bar(const int*const arr) {
   int k = arr[0];
   foo(arr);
   return k+arr[0];
 }

a clever optimizing compiler could load arr[0] only once (and keep the k in a local across call to foo)

It looks like gcc-4.9 is not able (or not willing) of such an optimization, but clang-3.5 is optimizing it (both with -O3 -fverbose-asm on Linux/x86-64).

BTW, it is not specific to C11, I believe that with C99 semantics the compiler is allowed to optimize also.

like image 119
Basile Starynkevitch Avatar answered Oct 21 '22 19:10

Basile Starynkevitch