Re: explicitly code a loop?
Sure, running sum(list) is fine, if you already have a list. However, consider that the data might not have been in a list, such that the code actually looked more like:
foreach (account in accountsList) {
(login,password)=db_login_fetch(account);
account.access(login,password);
exposure=account.exposure();
total_exposure+=exposure;
}
Sure, you could rewrite it. The other option, using sum, looks like this:
exposures=[];
foreach (account in accountsList) {
(login,password)=db_login_fetch(account);
account.access(login,password);
exposure=account.exposure();
exposures.append(exposure);
}
total_exposure=sum(exposures);
The code is longer. It requires more memory (perhaps quite a bit if there are lots of accounts). This code is assuming a nice list data structure with its own append function and memory management. If this is C, that's more complicated. Storing in a structure takes a bit more time, and it will be thrown away immediately. You can also mess up this code by mistake, as well. This would have prevented the += problem, but it doesn't prevent other problems.
I don't think this is really important; given that the data was in the form of numbers, adding them up or summing a list would both be very basic. However, if I had a different type of data that took more memory, was complicated to "add", or could take a while to access, I would prefer incremental addition rather than a list collection and subsequent summation.