Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
ASP.NET Site Performance Secrets

You're reading from   ASP.NET Site Performance Secrets Simple and proven techniques to quickly speed up your ASP.NET website

Arrow left icon
Product type Paperback
Published in Oct 2010
Publisher Packt
ISBN-13 9781849690683
Length 456 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Mattijs Perdeck Mattijs Perdeck
Author Profile Icon Mattijs Perdeck
Mattijs Perdeck
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

ASP.NET Site Performance Secrets
Credits
About the Author
About the Reviewers
1. Preface
1. High Level Diagnosis FREE CHAPTER 2. Reducing Time to First Byte 3. Memory 4. CPU 5. Caching 6. Thread Usage 7. Reducing Long Wait Times 8. Speeding up Database Access 9. Reducing Time to Last Byte 10. Compression 11. Optimizing Forms 12. Reducing Image Load Times 13. Improving JavaScript Loading 14. Load Testing

Foreach


The C# statement foreach is a convenient way to traverse an enumerable collection, but because it uses an enumerator it is also more expensive than a normal for loop.

The following code uses a trivial foreach loop:

int k = 0;
foreach loopforeach (int j in list)
{
k = j;
}

This code uses a for loop instead:

int k = 0;
int listLength = list.Count;
for (int i = 0; i < listLength; i++)
{
k = list[i];
}

For completeness, I also tested a loop that counts backwards to zero, rather than forwards to the list count:

int k = 0;
for (int i = list.Count - 1; i >= 0; i--)
{
k = list[i];
}

I used a List<int> with 1000 integers. On my machine, the results were:

Test

Time taken (ticks)

foreach 1000 List<int> accesses

168

for 1000 List<int> accesses

80

for backwards - 1000 List<int> accesses

75

This concludes that if you're counting every CPU cycle, you may want to look at tight foreach loops with very high numbers of iterations. Looping backwards will give you a very...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image