TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Is one double for loop better than two for loops?

1 pointsby redxbloodover 11 years ago
I mean, is: for(..){ for(..){ } }<p>better than for(..){} for(..){} ?<p>May it be in terms of running time, memory, etc. This may be a dumb question, if so, i&#x27;m sorry.

2 comments

mason240over 11 years ago
It&#x27;s not a dumb question, this idea is covered at the beginning of every data structures class and is described as Big O Notation.<p>The difference is the growth rate.<p>for(..){} for(..){} will grow linearly, or O(n).<p>Iterating over 10 items will be 20 loops, while iterating over 11 items will only be 22 loops.<p>for(..){ for(..){ } } grows exponentially, or O(n^2)<p>Here iterating over 10 items will be 100 loops, and increasing n by 1 (to 11) results in 121 loops.<p>Typically it preferably to user O(n) over O(n^2).<p>This probably explains it better than I can: <a href="http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/" rel="nofollow">http:&#x2F;&#x2F;rob-bell.net&#x2F;2009&#x2F;06&#x2F;a-beginners-guide-to-big-o-notat...</a>
评论 #6376431 未加载
itgover 11 years ago
Wouldn&#x27;t you need them for different purposes? A double for loop would go over a 2 dimensional array while a single for loop cannot.