Suppose that there exists a big-sized string, and I would pass this string variable into a specific function. What will be the best way for speed?
[Test]
1. Make 10,000,000 byte length string variable.
#define STRING_SIZE 10000000
string s;
for (int i = 0; i < STRING_SIZE; i++)
s += rand() % 256;
2. Pass this s string parameter into the following functions. Of course, s variable value does not change in each function.
#define SUB_STR "ABCDE"
size_t find_string (const string s) { return s.find(SUB_STR); }
size_t find_const_string (const string s) { return s.find(SUB_STR); }
size_t find_pointer_string (string* s) { return s->find(SUB_STR); }
size_t find_const_pointer_string (const string* s) { return s->find(SUB_STR); }
size_t find_reference_string (string& s) { return s.find(SUB_STR); }
size_t find_const_reference_string(const string& s) { return s.find(SUB_STR); }
3. Measure the elapsed time to complete the loop.
#define COUNT 100
begTick = timeGetTime();
for(i = 0; i < COUNT; i++)
find_string(s);
endTick = timeGetTime();
printf("find_string elapsed %u msec\n", endTick - begTick);
[Result]
Microsoft Visual Studio 2005 Relase mode. Optimization - Maximize Speed (/O2)
find_string elapsed 2257 msec
find_const_string elapsed 2244 msec
find_pointer_string elapsed 733 msec
find_const_pointer_string elapsed 733 msec
find_reference_string elapsed 732 msec
find_const_reference_string elapsed 733 msec
[Conslusion]
Keyword "const" does not result in an optimization code for a big-sized string parameter.
If a big-sized string variable should be passed into a function, pointer or reference type is desirable.
[Download]