473,385 Members | 1,445 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Performance test: for + foreach


Folks,
Ever since reading an interesting article in Linux Format on PHP whereby
suggested code writing was made that could enhance performance on a server,
I've started testing various bits of code everytime I found more than one
method to perform a single task. I timed each method to find which would
complete faster. I thought I'd share my most recent results which (I
believe) should help those write their programs to be more
clean/environmentally friendly on systems resources.

If you don't want to read further, basically, I created two identical tasks
except one used a "for" loop and the other used "foreach" loop. I found
"for" loops are almost ten percent faster to use when compared to "foreach"
loops when working on arrays.

My problem (or task pending which way you want to look at it):

I had a problem whereby I had a string that I wanted to cut to x number of
words - I wanted the cut to be clean (thus not cut in the middle of a word,
but cut between words)... My solution was to convert the string in to an
array, take each array element (a single word) and append it to a new
string - then check the length of the new string and make sure it had not
exceeded maximum length. Maximum length was dynamic because sometimes I
wanted the first ten (whole) words - sometimes more...

While reading the temporary array (that contained the words), I knew I could
perform a foreach($tmpArray as $wordCount=>$aWord) or I could perform a
"for" loop that incremented a numeric variable to the maximum number of
elements in the array of words.

Call me sad - but I then wondered if using foreach on an array was
lighter/heavier on the system then using a for loop... so I put both of them
to the test. My test script below records the speed of which would complete
first - a for loop, or a foreach loop when both were required to perform the
same routine inside the loop...

I discovered that using a for loop is about ten percent faster than using a
foreach loop. A foreach loop took 45seconds on my server to perform the
same test that took 42seconds using a for loop... It might not be much, but
every little bit helps, especially if you have several users on your system
at the same time drawing on resources used by PHP.

I'm interested in any comments anyone has to offer on this...

<?
// Execute each test $maxLoop number of times
$maxLoop=25;
// Our test array will contain
$maxArraySize=200000;

/////////////////////////////////////////////////////////////////////
// Create an array, $maxArrayLength elements in size - each element
// in the array will contain random strings
set_time_limit(100);
for($tmpA=0; $tmpA<$maxArraySize; ++$tmpA)
{ $randomString=mt_rand(0,$maxArraySize) . time();
$tmpArray[]=md5($randomString);
}

/////////////////////////////////////////////////////////////////////
// Select a random value from the array
$randomElement=round(mt_rand(0,$maxArraySize));
$randomValue=$tmpArray[$randomElement];

/////////////////////////////////////////////////////////////////////
// Start test 1
set_time_limit(100);
print("<br>Search for $randomElement $randomValue<br>");
$start=time();
for($tmpA=0; $tmpA<$maxLoop; ++$tmpA)
{ foreach($tmpArray as $key=>$value)
{ if("$value"=="$randomValue")
{ break; }
}
}
$endTest1=time()-$start;
/////////////////////////////////////////////////////////////////////
// Start test 2
set_time_limit(100);
$start=time();
for($tmpA=0; $tmpA<$maxLoop; ++$tmpA)
{ for($tmpB=0; $tmpB<$maxArraySize; ++$tmpB)
{ $value=$tmpArray[$tmpB];
if("$value"=="$randomValue")
{ break; }
}
}
$endTest2=time()-$start;
/////////////////////////////////////////////////////////////////////
print("<hr>Test 1 = $endTest1 seconds");
print("<hr>Test 2 = $endTest2 seconds<br>");
?>
--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet?
Jul 17 '05 #1
0 4274

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Randell D. | last post by:
Folks, A ng poster recently questioned their usage/creation of arrays and their correct syntax. I got the idea to performance test from a recent (excellent) PHP Tutorial article that was in Linux...
20
by: jeevankodali | last post by:
Hi I have an .Net application which processes thousands of Xml nodes each day and for each node I am using around 30-40 Regex matches to see if they satisfy some conditions are not. These Regex...
3
by: AK | last post by:
Hi Everyone, For Last a few weeks I have been involved with performance tuning of an application. I have observed that if I do a loop over a collection (ArrayList/HashTable) which has 50000...
15
by: MuZZy | last post by:
Hi, Consider this: ArrayList al = new ArrayList(); FillList(al); /// NOW TWO SCENARIOS: /// 1. for (int i = 0 ; i < al.Count ; i++)
18
by: Rune B | last post by:
Hi Group I was considering using a Generic Dictionary<> as a value container inside my business objects, for the reason of keeping track of fields changed or added and so on. - But how...
7
by: David Veeneman | last post by:
This is a very simple question, but for moe reason I can't find an answer. Do I take a performance hit if a foreach statement has to evaluate an expression? For example, consider the following:...
5
by: Markus Ernst | last post by:
Hello A class that composes the output of shop-related data gets some info from the main shop class. Now I wonder whether it is faster to store the info in the output class or get it from the...
6
by: semkaa | last post by:
Can you explain why using ref keyword for passing parameters works slower that passing parameters by values itself. I wrote 2 examples to test it: //using ref static void Main(string args) {...
12
by: Mark S. | last post by:
Hello, The app in question is lives on a Windows 2003 server with .NET 2.0 running IIS 6. The page of the app in question processes 2000 get requests a second during peak loads. The app uses...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.