473,795 Members | 2,834 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arrays + Performance surprise - curious for comments

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 Format magazine (which
dealt with performance).

The original poster had a reply from someone who had said using
$testArray[$keyName] was better (and proper) than $testArray["$keyName"]

I *had* believed this to be correct... but... against my better judgement, I
decided to test the assumption.

I did a simple test to confirm - Basically, a loop that performed a
conditional 'if' test a large number of times - One used the double quotes
around the array key, one went without. Other than that, the rest was the
same - the box was almost asleep too during the test with a single user and
no cron jobs or other activity. To make sure, I ran the script twice, ten
minutes apart.... and the results?

Strangely, the test *with* the double quotes took half the time. We're
talking about Test 1 taking 85seconds and test 2 taking 152seconds

I'm curious on anything anyone can add to this - It got me thinking that if
something is faster, is it right/recommended practice?

My test script is below....

--
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?

<?
// Perform a test $maxLoop number of times, count the number of seconds
// it takes to complete the loop - Test 1 has the array element named
// inside double quotes, Test 2 excludes the double quotes
set_time_limit( 250);
$testArray=$_EN V;
$maxLoop=100000 ;
/////////////////////// Test 1 //////////////////// This took 85seconds to
complete
$start=time();
for($loopMany=0 ; $loopMany<$maxL oop; ++$loopMany)
{ foreach($testAr ray as $elementName=>$ elementValue)
{ if($testArray["$elementNa me"]=="HOST")
{ $thisHost="$ele mentValue"; }
}
}
$end=time();
$difference=$en d-$start;
print("<br>Dura tion 1: $difference<hr> ");

set_time_limit( 250);
$testArray=$_EN V;
$maxLoop=100000 ;
/////////////////////// Test 2 //////////////////// This took 151 seconds to
complete
for($loopMany=0 ; $loopMany<$maxL oop; ++$loopMany)
{ foreach($testAr ray as $elementName=>$ elementValue)
{ if($testArray[$elementName]=="HOST")
{ $thisHost="$ele mentValue"; }
}
}
$end=time();
$difference=$en d-$start;
print("<br>Dura tion 2: $difference<hr> ");
?>

--
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
3 2592

"Randell D." <yo************ **************@ yahoo.com> wrote in message
news:Br******** *************** *@news2.calgary .shaw.ca...
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 Format magazine (which
dealt with performance).

The original poster had a reply from someone who had said using
$testArray[$keyName] was better (and proper) than $testArray["$keyName"]

I *had* believed this to be correct... but... against my better judgement, I decided to test the assumption.

I did a simple test to confirm - Basically, a loop that performed a
conditional 'if' test a large number of times - One used the double quotes
around the array key, one went without. Other than that, the rest was the
same - the box was almost asleep too during the test with a single user and no cron jobs or other activity. To make sure, I ran the script twice, ten
minutes apart.... and the results?

Strangely, the test *with* the double quotes took half the time. We're
talking about Test 1 taking 85seconds and test 2 taking 152seconds

I'm curious on anything anyone can add to this - It got me thinking that if something is faster, is it right/recommended practice?

My test script is below....

--
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?

<?
// Perform a test $maxLoop number of times, count the number of seconds
// it takes to complete the loop - Test 1 has the array element named
// inside double quotes, Test 2 excludes the double quotes
set_time_limit( 250);
$testArray=$_EN V;
$maxLoop=100000 ;
/////////////////////// Test 1 //////////////////// This took 85seconds to complete
$start=time();
for($loopMany=0 ; $loopMany<$maxL oop; ++$loopMany)
{ foreach($testAr ray as $elementName=>$ elementValue)
{ if($testArray["$elementNa me"]=="HOST")
{ $thisHost="$ele mentValue"; }
}
}
$end=time();
$difference=$en d-$start;
print("<br>Dura tion 1: $difference<hr> ");

set_time_limit( 250);
$testArray=$_EN V;
$maxLoop=100000 ;
/////////////////////// Test 2 //////////////////// This took 151 seconds to complete
for($loopMany=0 ; $loopMany<$maxL oop; ++$loopMany)
{ foreach($testAr ray as $elementName=>$ elementValue)
{ if($testArray[$elementName]=="HOST")
{ $thisHost="$ele mentValue"; }
}
}
$end=time();
$difference=$en d-$start;
print("<br>Dura tion 2: $difference<hr> ");
?>

--
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?


As 'BKDotCom' points out in another post - I got something wrong in my test
8(...

*cough cough*
Your test 2 took 66 seconds.
you didn't reinitialize $start after test1 compleated... therefore
152 seconds is the total time your script ran.

so:
86 sec for test 1 (quotes)
66 sec for test 2 (no quotes)
152 sec: total

but, bonus points to you for actually taking the time to research this.
Jul 17 '05 #2
I tried following:

<?php
$maxLoop=100000 ;
$iterations=20;

$start=time();
for ($i=0;$i<$itera tions;$i++){
unset($test);
for($loopMany=0 ; $loopMany<$maxL oop; ++$loopMany)
{
$test[]=1;
}
}
$end=time();
$difference=$en d-$start;
print("<br>Dura tion 0: $difference<hr> ");

$start=time();
for ($i=0;$i<$itera tions;$i++){
unset($test);
for($loopMany=0 ; $loopMany<$maxL oop; ++$loopMany)
{
$test[$loopMany]=1;
}
}
$end=time();
$difference=$en d-$start;
print("<br>Dura tion 1: $difference<hr> ");

$start=time();
set_time_limit( 250);
for ($i=0;$i<$itera tions;$i++){
unset($test);
for($loopMany=0 ; $loopMany<$maxL oop; ++$loopMany)
{
$test["$loopMany"]=1;
}
}
$end=time();
$difference=$en d-$start;
print("<br>Dura tion 2: $difference<hr> ");
?>

and got these results:

$test[] 18secs
$test[$loopMany] 22secs
$test["$loopMany"] 50secs

I think the difference is due to how PHP handles quoted strings. PHP
first has to parse the quoted string and replace all variables with
their values (probably creates a temp string for this operation) and
after that it can use the resulted string as array index. When
variable is used directly PHP doesn't have to do this extra step.
But I'm only guessing, I have no idea of the inner workings of PHP.

- allan savolainen
Jul 17 '05 #3
Allan Savolainen wrote:

I think the difference is due to how PHP handles quoted strings. PHP
first has to parse the quoted string and replace all variables with
their values (probably creates a temp string for this operation) and
after that it can use the resulted string as array index. When
variable is used directly PHP doesn't have to do this extra step.
But I'm only guessing, I have no idea of the inner workings of PHP.

- allan savolainen


Allan,

You're exactly right. Putting a variable in double-quotes is called
string interpolation. It not only requires this extra step, but calls
up a whole subset of parsing routines to break the string into
constituent parts. (In some instances, it's even faster to concatenate
static strings instead of relying on interpolation.) You should also
run your test using all of the different quoting methods:

$mykey = 'key';
$array[]
$array[key]
$array['key']
$array["key"]
$array[$mykey]
$array["$mykey"]

[Additional Tests:]
$k1 = 'k'; $k2 = 'e'; $k3 = 'y';
$array["$k1$k2$k3"]
$array[$k1.$k2.$k3]
$array['k'.'e'.'y']

You should find out that using single-quoted strings are slightly faster
than the same double-quoted string. (It doesn't trip the interpolation
system, but just assumes the string is a constant.)

It's not all that hard to figure out what PHP is doing. The Zend
language is pretty similar to C, so you should be able to browse the
source code to PHP and get a good idea of "the inner workings of PHP."
I do all the time just to figure out what the best way to do something
is. At first, finding the code can be a little daunting (there's a
couple hundred source files). But, a good text searching program will
go a long way in finding the information you need. It might also help
to do a little research on the Apache API, since PHP is pretty
integrated into Apache for certain things (especially when you're using
it as a module and not as a CGI binary).

Does anybody know if heredocs are faster or slower than quoted strings?

Take care,
Zac

Jul 17 '05 #4

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

Similar topics

25
3493
by: Brian Patterson | last post by:
I have noticed in the book of words that hasattr works by calling getattr and raising an exception if no such attribute exists. If I need the value in any case, am I better off using getattr within a try statement myself, or is there some clever implementation enhancement which makes this a bad idea? i.e. should I prefer: if hasattr(self,"datum"): datum=getattr("datum") else: datum=None
10
2033
by: KN | last post by:
I know both are pretty much the same and it comes down to personal choice. But I have to make the choice for the team. Things so far that I am considering 1. XML documentation in C# -- thats good.. not there in VB.net?? 2. Some language features of VB.Net like Redim(makes it easier for developers), but not good enough reason. 3. C# is in more like standard languages and key words used are more
12
9199
by: Dave Theese | last post by:
Hello all, I'm in a poition of trying to justify use of the STL from a performance perspective. As a starting point, can anyone cite any benchmarks comparing vectors to plain old statically-declared arrays? I'll also be looking at the other STL containers later... Also, I'd appreciate any comments anyone has on the suitability of the little program below for comparing vectors and arrays. One obvious shortcoming is that it uses...
1
2729
by: James dean | last post by:
I done a test and i really do not know the reason why a jagged array who has the same number of elements as a multidimensional array is faster here is my test. I assign a value and do a small calculation. Even if i initialise the jagged array inside the function it is still much faster. Are these results correct?. If i put the initialisation loop in the constructor its ridiculously faster but even here its 4 times faster...is this correct?...
2
1935
by: Michael Fitzpatrick | last post by:
I have a DLL written in C. This DLL reads a text file and creates a several very large arrays, 500,000 points and even larger. I would like the get the data in VB.Net so that I can plot it. Presently I am creating an equally sized array in VB and copying the data from the DLL's array into the VB array. There must be a better way. I looked into using a SAFEARRAY but it looks to me that VB.Net doesn't use them as a native array structure....
36
2505
by: mrby | last post by:
Hi, Does anyone know of any link which describes the (relative) performance of all kinds of C operations? e.g: how fast is "add" comparing with "multiplication" on a typical machine. Thanks! -- B. Y.
3
1935
by: yonil | last post by:
Over the years of using C++ I've begun noticing that freestore management functions (malloc/free) become performance bottlenecks in complex object-oriented libraries. This is usually because these functions acquire a mutex lock on the heap. Since the software I'm writing is targetted for a number of embedded platforms as well as the PC, it's somewhat difficult to use anything but the standard implementation given with the compiler. I've...
1
4320
by: Erland Sommarskog | last post by:
I am glad to announce that there is now a version of my article "Arrays and Lists in SQL Server" for SQL 2005 available on my web site. THe URL for the article is http://www.sommarskog.se/arrays-in-sql-2005.html. If you are curious about the performance numbers they are in an appendix at http://www.sommarskog.se/arrays-in-sql-perftest.html. The old version of the aritlce remains, as the new article covers SQL 2005 only. The old...
5
6287
by: =?Utf-8?B?TWFyaw==?= | last post by:
Hi... I've been trying to improve the performance of our xml handling, so I've been doing some timing tests lately and ran across something I thought odd - XPathDocument seems slightly slower than XmlDocument. I've run the tests several times and have tried to eliminate extraneous variables like disk access but every time, XPathDocument comes up slower by a few percent. I'd expected it to be faster since it's a read-only...
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9522
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10443
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10216
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10002
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7543
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.