Is it good practice to reference each constant line?

Code A:

string a = "Hello World";

for (int i=0; i<1000000; ++i) 
     const string b = a;

Code B:

string a = "Hello World";

for (int i=0; i<1000000; ++i) 
     const string &b = a;

If I ran 2 codes separately and measured the processor time, code B was about 2.5 times faster than code A.

Except primitive types, such as char, int, float... I learned that quickly get a link to the original, but not copy it.

Although in most cases the difference is almost not taken into account, can it be considered good practice to always refer to a type const string(and other non-primitive types)?

+4
source share
2 answers

, const , . , , ; , , , undefined. , .

const - . , , , , .

+3

, .

  • . ?
  • (, )?

:
, const.
, sizeof , sizeof(void*), const.
.

, .

, - , , , , .

, .

+2

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


All Articles