473,395 Members | 1,556 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,395 software developers and data experts.

Efficiency question: Overwrite array value, or ask if it is set?

Hi

While looping through an array I extract all keys on the fly, as in this
example:

$data = array(
array('name' ='Helen', 'age' ='40'),
array('name' ='Mark', 'email' ='****@xyz.com', 'age' ='90'),
);
$keys = array();
foreach ($data as $row) {
foreach ($row as $key =$value) {
// do other things here
$keys[$key] = 1;
}
}
$column_names = array_keys($keys);

Now my question is about the line
$keys[$key] = 1;

This overwrites existing entries and thus creates a set of unique keys.
This could also be done without overwriting:
if (!isset($keys[$key])) $keys[$key] = 1;

So I wonder which is more efficient - overwriting the array entry at
every loop, or checking for it with the if statement.

Thanks for a comment
Markus
Jul 6 '06 #1
4 2180
Markus Ernst wrote:
Hi

While looping through an array I extract all keys on the fly, as in
this example:

$data = array(
array('name' ='Helen', 'age' ='40'),
array('name' ='Mark', 'email' ='****@xyz.com', 'age' ='90'),
);
$keys = array();
foreach ($data as $row) {
foreach ($row as $key =$value) {
// do other things here
$keys[$key] = 1;
}
}
$column_names = array_keys($keys);

Now my question is about the line
$keys[$key] = 1;

This overwrites existing entries and thus creates a set of unique
keys. This could also be done without overwriting:
if (!isset($keys[$key])) $keys[$key] = 1;

So I wonder which is more efficient - overwriting the array entry at
every loop, or checking for it with the if statement.

Thanks for a comment
Markus
ISTR a general rule that said that assignments were more efficienct that
tests.
If this is not the case, then the answer to your question depends on whether
in most cases you will end up doing the assignment, or whether in most cases
the value is already set.
If the former is true, then it is certainly not more efficient, if the
latter then it may be. This is where knowing something about the data is
required.

I think that all makes sense!
Jul 6 '06 #2
I understand what you are doing. I changed it a little which I believe
is a little more intuitive. It may even be faster.

$data = array(
array('name' ='Helen', 'age' ='40'),
array('name' ='Mark', 'email' ='...@xyz.com', 'age' ='90'),
);
$column_names=array();
foreach ($data as $row) {
foreach ($row as $key =$value) {
// do other things here
if (!in_array($key,$column_names)) $column_names[]=$key;
}
}
Markus Ernst wrote:
Hi

While looping through an array I extract all keys on the fly, as in this
example:

$data = array(
array('name' ='Helen', 'age' ='40'),
array('name' ='Mark', 'email' ='****@xyz.com', 'age' ='90'),
);
$keys = array();
foreach ($data as $row) {
foreach ($row as $key =$value) {
// do other things here
$keys[$key] = 1;
}
}
$column_names = array_keys($keys);

Now my question is about the line
$keys[$key] = 1;

This overwrites existing entries and thus creates a set of unique keys.
This could also be done without overwriting:
if (!isset($keys[$key])) $keys[$key] = 1;

So I wonder which is more efficient - overwriting the array entry at
every loop, or checking for it with the if statement.

Thanks for a comment
Markus
Jul 6 '06 #3
*** Markus Ernst escribió/wrote (Thu, 06 Jul 2006 10:52:50 +0200):
So I wonder which is more efficient - overwriting the array entry at
every loop, or checking for it with the if statement.
A quick dirty benchmark with loops and microtime(), using the code you
posted, shows that assigning is slightly faster that testing, running from
command line. The saving ranges from 3% to 6%.

If you're interested in these issues you may like Xdebug and WinCacheGrind:

http://xdebug.org/
http://sourceforge.net/projects/wincachegrind/

--
-+ http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
++ Mi sitio sobre programación web: http://bits.demogracia.com
+- Mi web de humor con rayos UVA: http://www.demogracia.com
--
Jul 6 '06 #4
Markus Ernst schrieb:
While looping through an array I extract all keys on the fly, as in this
example:

$data = array(
array('name' ='Helen', 'age' ='40'),
array('name' ='Mark', 'email' ='****@xyz.com', 'age' ='90'),
);
$keys = array();
foreach ($data as $row) {
foreach ($row as $key =$value) {
// do other things here
$keys[$key] = 1;
}
}
$column_names = array_keys($keys);

Now my question is about the line
$keys[$key] = 1;

This overwrites existing entries and thus creates a set of unique keys.
This could also be done without overwriting:
if (!isset($keys[$key])) $keys[$key] = 1;

So I wonder which is more efficient - overwriting the array entry at
every loop, or checking for it with the if statement.
Thank you all for your inputs! I finally tested the versions suggested
with my real data.
Version 1: $keys[$key] = $key;
Version 2: if (!isset($keys[$key])) $keys[$key] = $key;
Version 3: if (!in_array($key, $keys)) $keys[] = $key;

Though it was only a few lines, all versions in the same script, the
rankings differed from call to call; maybe I could say that version 1
tends to be fastest when total execution is fast, and version 3 tends to
win when total execution is slower.

Anyway the range was between 0.05 and 0.1 second, which was not really
the reason for my total execution time of 25-35 seconds! (Going on
measuring and optimizing other parts of the code, I reduced it to 3-5
seconds now!)
Jul 7 '06 #5

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

Similar topics

7
by: csx | last post by:
Hi everyone! two quick questions relating to arrays. Q1, Is it possible to re-assign array elements? int array = {{2,4}, {4,5}}; array = {2,3}
8
by: Kin Pang | last post by:
Hi, I have a routine where I'm using a std::map from a pair of ints to double for caching evaluation results. The cache depth could be upto say 1000 in depth. However, my application needs to...
17
by: Christopher Benson-Manica | last post by:
Yesterday I changed some code to use std::vectors and std::strings instead of character arrays. My boss asked me today why I did it, and I said that the code looks cleaner this way. He countered...
38
by: aaronfude | last post by:
I'm working on a scientific computing application. I need a class called Element which is no more than a collection of integers, or "nodes" and has only on method int getNode(int i). I would...
31
by: mark | last post by:
Hello- i am trying to make the function addbitwise more efficient. the code below takes an array of binary numbers (of size 5) and performs bitwise addition. it looks ugly and it is not elegant...
3
by: Mike Cain | last post by:
I have an odd situation I'm trying to understand..... I'm using MS VS 7.0 C++ with the MFC CBuffer class. If I do this: #define NUM_ELEMENTS 2 CBuffer<char, 512 x; CBuffer<char, 512 ...
9
by: anon.asdf | last post by:
In terms of efficieny: Is it better to use multiple putchar()'s after one another as one gets to new char's OR is it better to collect the characters to a char-array first, and then use...
5
by: Lars | last post by:
I need to multiply to large matrices (of type double), where one is "dense" (mostly non-zero entries) and the other is "sparse" (mostly zero entries). Will it be more efficient to check for...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...

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.