sergey.lukoshkin@gmail.com kirjutas:
> On Jun 7, 9:27 pm, Paavo Helde <nob...@ebi.ee> wrote:
>
>> You should, lots of it will be included in the next C++ standard.
>>
>>
>>
>> > int main()
>> > {
>> > static std::string str;
>> > static std::istringstream istr;
>> > static unsigned val;
>>
>> main() is called only once so the keyword 'static' does not change
>> anything here. Why do you think 'static' is needed?
>>
>> And why do you define them here, not inside the loop where they are
>> used? Would have avoided all the trouble in the first place...
>
> Well, I agree with you. In this case there is no benefit of using
> static keyword. But if I take the contents of main() and put it in my
> function that I'm going to call many times at a runtime it will reduce
> the cost of function calling.
Are you sure? Have you measured this? If the variables are not local, the
compiler has harder times to optimize the code. If the variables are
local, the compiler can in principle optimize they all away. In your
current code you need an extra call to clear() function as well, which
would not be needed in case of local variables.
Also, by using such static variables you make your function non-reentrant
and thus hard and slow (external locking needed) to use in multithreaded
programs, with no apparent reasons for that.
IOW, the sooner you wander away from the perils of premature optimization
the better! For deciding what would be the best optimization you need to
be an expert, and even then you have to measure your hypothesis. Here I
think a possible optimization could be to use a certain C function
instead of multiple C++ objects construction, but I'm not sure at all.
Regards
Paavo