CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming Did you compared between loops, for vs foreach?

Did you compared between loops, for vs foreach?

Rana Ahsan August 24, 2010 1 Comment


 Did you compared between loops, for vs foreach?    

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 ๐Ÿ™‚

Related

Filed Under: Programming Tagged With: performance, php

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Using GIT Plugin For Netbeans IDE

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 ยท Streamline Pro Theme on Genesis Framework ยท WordPress ยท Log in