Solved Performance of foreach() while using method as container.
-
Hello Everyone,
I need an explanation about how foreach works or which is better to use?
QStringList mainfilelist; QStringList getfiles() { //suppose we have already filled some data in mainfilelist return mainfilelist; } //------------------------------- //1st method foreach(auto var, getfiles()) { //some processing } //2nd method QStringList filelist = getfiles(); foreach(auto var, filelist) { //some processing }
Now considering performance-wise, whish method is good to implement?
Please provide your suggestions,
Thanks.
-
@npatil15 There should not be any difference as in the first method getfiles() will be called once and the iteration will be then done in the same way as in the second.
-
Okay, thanks, that's my confusion, I thought it calls method every time and gets the next file, but it's wrong.
-
@npatil15 said in Performance of foreach() while using method as container.:
I thought it calls method every time and gets the next file
No, it calls the function once and iterates over the list this function returns.
-
@npatil15 keep in mind, that foreach is marked obsolete and (IIRC) will no longer be available in Qt6
When you write new code, you're supposed to either use the std::for_each or preferably the ranged for loop