• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Did you compared between loops, for vs foreach?

Did you compared between loops, for vs foreach?

August 24, 2010 by Rana Ahsan 1 Comment

Variable Declaration Tutorial

When I was student and did assignments, most of the time, I just wanted to get rid of the task and gave up as soon as we got a result which is or around acceptable. We though that, we will try better while doing professionally. But, as I am now in professional web application field and had chance to go through many web applications, i just experienced that, most of us are still there where we were before. That means, still we are doing a code just for get a thing done, don’t even think for a moment, is there any better than what we got? Well, to become an expert, reliable programmer, this can be the worst practice one can do. We should think all the time that we are learning, not that we have already learned many things and should keep an eye on even a very tiny part of the development and if possible make that better. I am just going to give such a simple example here to show how different approach may get significance difference in performance. This is a comparison of two popular loops used very much often in programming and development ‘for vs foreach loop’ with small snippet of PHP code examples as well to test with.

Are You An Ancient Programmer?

Who have their background from cse graduation, and have initial knowledge like variable declaration, basic syntax, should also be well-known of the ‘for loop’ term/keyword. This is the one c/c++ language have(c/c++ is vastly used in universities for beginning lesson of programming and foreach isn’t available there in c/c++). So, they come to in development field and work with languages like php/c#, they may like to stick to their comfortable ‘for’ loop. However, its general thought that, as ‘foreach’ loop is introduced there, there must be some advantages that it provides. Lets get a test, is it true?

Let’s Compare For Vs Foreach:

The following code samples are written in php under codeigniter framework’s benchmark library(it just to save my time as i am currently using these 😀 ), if you are using other languages, consider this as a pseudo code implement in your language way. There shouldn’t be any problem to implement this to any programming language. If you have experience with php/codeigniter, then you are lucky, just copy paste this code and test 🙂 .

                $data = array();
		for($i=0;$i<500000;$i++){
				$data[$i] = rand();
			}
		
		$this->benchmark->mark('code_start');
			for($i=0;$i<500000;$i++){
				;
			}
		$this->benchmark->mark('code_end');
		echo $this->benchmark->elapsed_time('code_start', 'code_end');
		echo "<br/>";
		$this->benchmark->mark('code_start');			
			foreach($data as $row){
				;
			}
		$this->benchmark->mark('code_end');

i have got 2 seconds difference between these two loops(one later one ran in around 3 seconds while first one ran in around 5 seconds). So, foreach loop won the ‘battle of for vs foreach’ here. However, you might be thinking, we won’t need such big loop; May be not in all cases, but there are some cases where long loops may be needed, like update big product database from web service/xml/csv etc. And, this example is only to aware you about the performance difference between them.

But, yes, they both have some exclusive use where they should exclusively because of extreme easiness/optimization. Like, if you are working in a loop where, on a certain condition the loop can be terminated. In this case, for loop will do the work with the most flexibility. On the other hand, if you are taking every objects/item from a list array and processing them, in this case, foreach will serve you best.

Any Other Loop Except For And Foreach?

There is also an another loop named ‘while'(you can also compare its performance with the others yourself) with which, we may also replace both for and/or foreach usually, but words are same there too. First, see which one best suites and provides best flexibility to get the work done and then if two looks similar, use the best performed one. And yes, sometimes we do have in a hurry/urgent where we always have to run swiftly(this is true most of the time in case of freelancers 🙂 ), and we really don’t get time to think of these much. But, if we do this when we get the chance, this may become a good habit that will help us do better than others in the long run. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: performance, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Trackbacks

  1. Getting Started With LinQ to SQL C# Tutorial | codesamplez.com says:
    January 28, 2011 at 2:02 am

    […] can be used, however foreach is much better in performance(to know details, you can refer to my for vs foreach article). here is the code samples for using the foreach loop for traversing through all result […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023