Modern CPUs have gotten so ridiculously fast that for most business applications we don't need to worry about optimizing the code we are writing. On the other hand, network calls like getting a record from database consume an eternity of CPU cycles. For example consider the following code example:
foreach (var item in itemList){ var data = MakeANetworkCallToDatabaseAndGetData(item.Id); Process(data);}
On the face of it, there is nothing wrong with this. The code works and even performs fine when the items in the list are less. But you will start to see things slow down when the item list grows. So how to solve this problem?
var allIds = itemList.Select(x => x.Id).ToList();var dataList = MakeANetworkCallToDatabaseAndGetData(allIds);foreach (var data in dataList){ Process(data);}
As you can see in above code, we have reduced the network call to just one and process it once we have everything in memory. Things are much faster now!Obviously, this does not apply to all situations. If the retrieved object is too large and you try to load everything at once, you will run out of memory. So there are exceptions. But in most situations, keeping this simple trick in mind will help you write better performing code.
When in doubt, remember,
CPU cycles are cheap but network calls are costly.
yea yea i dnt care
ReplyDelete