For loop vs Iterator
I'm writing an application in which performance will be quite important and was looking into my collection classes. I recently saw the move towards using Iterator instead of for loops, while loops to retrieve objects from a List. I wanted to test to see which performed better and I saw that for about 1,000,000 Integer objects, an Iterator was 100ms slower in time in both Vector and ArrayList than a for loop using gets.
1) Is the main cost the creation of the Iterator object?
2) If I'm not worried about manipulation of my List while I'm retrieving objects and I will always be using a List in which I can always pull indexes (instead of say using HashSet)... is there any reason to use Iterator instead of a for loop?
-- I read the recent tech tip on this and was just wondering if anyone had any other ideas of why to choose Iterator over for/while loops.
Thanks.
The purpose of Iterator
The purpose of the Iterator pattern is to handle the traversal of a collection of objects.
The advantages of Iterator has over other straightforward ways
The direct access methods provided by some collection classes may not be as efficient or simple as using iterator pattern. And because the iterator keeps its own state, multiple traversals can be performed on a single collection simultaneously.
An iterator hides the internal representation of the collection from the classes that need to access the contents of these collections.
An Iterator pattern provides a consistent and sometimes efficient way to access the objects or values in some collections.
What problems can arise if collection is changing?
While using iterator, the changes of a collection such as that adding new elements or deleting old elements can result in inconsistency of the data, for example some objects may be missed or accessed more than once.
How can they be avoided?
A simple way is to make a copy of the collection and work on this copy but this can be very costly in terms of memory and time.
Design a method that notifies the iterator whenever the collection is changed, and as soon as the change happens the iterator class throws an exception or restart whichever appropriate.
A better way would be implements methods that monitor the changes and adjust the iterator and the results so they are consistent to the contents of the collection at any time.
There are no general solutions to this problem and under different circumstance the proper solutions vary, however it is a good practice to taking possible changes of the source collections into account while designing the iterator, and it may be worth to let the user aware of the occurrence of any changes.
Similar Messages
-
For loop 1 iteration execution time
Hi,
what is the time taken of for loop 1 iteration without code inside.How to calculate this Execution time.Ravindranath.K wrote:
Hi,
what is the time taken of for loop 1 iteration without code inside.How to calculate this Execution time.
No code in the FOR loop? It will not use any time because the compiler will optimize it out.
Why do you even need to know?
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines -
For loop stops iterating at first page
I have a loop that applies a paragraph style but it stops iterating at the first page of the document.
I need it to apply the style to the entire document...can't figure out why this isn't working.
Here is my script:
var myDocument = app.activeDocument;
var myParagraphStyle = myDocument.paragraphStyles.item("Paragraph Style");
myDocument.pages.item(0).textFrames.item(0).paragraphs.item(0).appliedParagraphStyle = myParagraphStyle;
var paragraphs = myDocument.pages.item(0).textFrames.item(0).paragraphs
for( i = 0; i < paragraphs.length; i++)
var paragraph = paragraphs.item(i)
paragraph.applyParagraphStyle(myParagraphStyle, true);
Thank youmyDocument.pages.item(0).textFrames.item(0).paragraphs.item(0).applied ParagraphStyle = myParagraphStyle;
Why do you have this line, when you iterate through the paragraphs later? (BTW: between "applied" and "ParagraphStyle" is a space)
But I think the problem is that you forgot two semicolon here:
var paragraphs = myDocument.pages.item(0).textFrames.item(0).paragraphs
(BTW: you should also call it "var myParagraphs ..." or something like that.)
and here:
var paragraph = paragraphs.item(i) -
Which is better ? for loop or iterator ??
Hi,
I have one array list having more than 100 objects in it.
I have two way to ietrator.
1.
for(int i=0; i<list.size(); i++)
Object o = list.get(i);
2.
Iterator i = list.getIterator()
while(i.hasNext())
Object o ...
which is better in performance ??Well okay. It's an easy optimization but I guess Sun
doesn't want to "bail out" people who don't know
their data structures.It won't always be optimal, though. If you use
iterators and don't iterate the whole way through
every time, it would degrade performance. It's hard
for them to make assumptions about how you will
access the data. So you punish people who do use it
properly if you do that.I don't know. The optimization I suggested is isolated to random accesses in the linked list only. Say you access index 5. The node pointer corresponding to 5 is stored and if the next access is index 6 the node pointer you're looking for is pointer.next. There's no need to walk the list from the beginning. -
How to use no of iteration of for loop as the input for the for loop
hi all,
i wanna need some help here..
i'm using for loop to iterate to ceratin no of iteration.. then, i would like to use back the no of iteration as the input of 'N' for the next iteration..
in other word, eg:
1st run:
i insert a control to 'N', let say 80
then the iteration run until 80-1 = 79..
2nd run:
i need to insert the no of "N", let say a control of 120.. i want the loop run for "120 - 79", where the 79 is the no of previous run..
easy to say,
how can i connect the "i' as a control to ''N''
n how to make a "run' or ' GO' and ''stop'' button in the front panel and block diagram after the first run without using the stop and run from the labview window
thanks..Jim
You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice
Attachments:
Untitled 2.vi 9 KB -
A tunneled Excel refnum goes from a valid value to a NULL between iterations of a For Loop?
How would a tunneled Excel refnum go from a valid value to a NULL between iterations of a For Loop?
For
some reason this works find in one VI and when executed and not in
another. Here's screen shots of the highlighted execution with probes
appropriately. The "Open" refnum is passed into "Performance Test -
Write Data To Files.vi". That's where the trouble is. You can see
that it goes into the For Loop. The first iteration is okay, but the
second and subsequent iterations have the refnum NULL. See images
below.
(I don't know how to delete an accidental double post, sorry)
Message Edited by James DiLiberto on 01-22-2008 01:48 PM
Attachments:
Second Iteration1.jpg 158 KB
First Iteration1.jpg 145 KB
Second Iteration Error Dialog1.jpg 20 KBIs there any chance that the Insert Data Into Excel VI is closing the reference or that it is closed anywhere else (e.g. through a local or by having its owner destroyed)?
I wouldn't expect the numeric value of the reference to change to 0, but since ActiveX is an external resource, I suppose that it's possible that the probe shows the number only if the resource is actually accessible.
Try to take over the world! -
The speed of the "for loop iteration"
Hi all:
I have written a short mini program just to test out the speed of a "for loop iteration"
package generator;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
private static long tmp = 0;
public static int count=0;
public synchronized long getValue(){
long value = 0;
value = 10 * System.currentTimeMillis();
if(value == tmp){
value++;
count++;
tmp = value;
return value;
public static void main(String[] args) {
for (int i=0;i<1000;i++){
getValue();
System.out.println("count is " + count);
}And i find that on average, count will be a value between 498-500, which probably means that on average the speed of a for loop is around 0.5 ms. But I guess the speed of the "for loop " iteration is also very much CPU dependent, could somebody possibly give me some education on this issue :) ?
Also, anybody know exactly how System.currentTimeMillis works? For example, how does it get the current time from the OS, etc. let me know.
Again, Many many thanks...Hi all:
I have written a short mini program just to test out the speed of a "for loop iteration"You will find the overhead of the getValue() call, the increments and most importantly the System.currentTimeMillis() is what you are timing.
public static void main(String args[]) {
int ITER = 1000000000;
long start = System.currentTimeMillis();
for(int i=0;i<ITER;i++);
long end = System.currentTimeMillis();
System.out.println("Iterations per sec="+ITER*1000L/(end - start));
}Prints the following Iterations per sec=576368876Running on a 1.8 GHz Intel/Windows2000 -
Handle Error in for Loop and finish the iteration
I am using a for Loop now i encounter an error.
i want to handle this error but after that carry on with iteration of the loop.
Any Parallel to "Continue" in JAVA or any other solution for this...
Please Suggest.You can use pl/sql block with exception inside the loop
Re: Continue beyond expcetion in proc...
Message was edited by:
jeneesh -
Reasons why to use Iterator for List rather than for loop ?
when i use the iterator and for loop for traversing through the list. it takes the same time for iterator and also for for loop. even if there is a change it is a minor millisecond difference.
what is the actual difference and what is happening behind the traversing list through iterator
if we are using we are importing extra classes ...if we are using for loop there is no need to import any classesIf you have an array-backed collection, like an ArrayList, then the difference between using an iterator and get() will be negligible.
However, if you have a linked list, using get() is O(n^2) whereas iterator is O(n).
So with an iterator, regardless of what your underlying data structure, a list of 100,000 elements takes 1,000 times as long to iterate over as a list with 100 elements. But using get() on a LinkedList, that same 100,000 element list will take 1,000,000 times as long as the 100 item list.
There's no real benefit to ever using get()
Side note: I've been comparing iterators to get(), not iterators to for loops. This is because whether it's a for or a while has nothing to do with whether you use an iterator or get(). The way I use iterators is for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Foo foo = (Foo)iter.next();
} -
How to save a chart after each iteration in a for loop?
Hello,
I have written code which initializes a spectrometer. Once initialized, if the "Capture" button is pushed, the spectrometer takes a new spectrum three times (see for loop) every second. This spectrum is displayed as a chart in my front panel. My code runs fine...it will update the spectrum every second.
However, I want to be able to save each of these three iterations as separate graphs. Basically, I want to click "Capture" and have my code save three charts to a specified folder. How do I go about doing this?
I've attached my VI.
Thanks.
Solved!
Go to Solution.
Attachments:
Spectrometer Iteration.vi 444 KBUse Build Array to make a 2D Array of your X and Y data and use Write To Spreadsheet File to save the data.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines -
How to output data outtside a for loop every 10 iterations​?
Hi friends,
does any body help me to sort out this problem?
please check the attchement for my vi.
all i want is output data from inside for loop to outside for loop every 10 iterations. please do not use local variable.
Many thanks
dan
Attachments:
output.vi 16 KBHi Dan,
I am not sure what you want to do every 10 iterations with the value outside, but If you want to update your graph every 10 iterations use the following way:
If you want to handle the specific value every x iterations outside the loop you could either use queues or notifieres.
BR,
ThSa
Message Edited by ThSa on 08-23-2006 09:05 PM
http://www.newgistics.com
Attachments:
1.png 6 KB -
I stuck with a problem that I am using FOR loop for generating repeating nodes.
Now when I concat the generated node in the main node then I got only last iteration of that FOR loop.
can anybody suggest me a way to handle this error....
FOR i IN 1..pl_phone_tab.Count
LOOP
SELECT xmlelement("Phone"
,xmlelement("PHONETYPE",xmlattributes('01' AS "dmnADRP_PHONETYPE"),pl_phone_tab(i).p_phtype_tab)
,xmlelement("PHONENUM",pl_phone_tab(i).p_phnum_tab)
,xmlelement("PRIMARY_CONTACT",pl_phone_tab(i).p_prcon_tab)
INTO p_phone_xml
FROM dual; END LOOP;
SELECT xmlelement("PhoneInfo"
,xmlconcat(p_phone_xml))
INTO p_phone_info_xml
FROM dual;
here I am getting only one node but there has to be two nodes for PHONE nodeNot that I'm encouraging you but here are two standalone examples explaining how to do what you want :
1) Loop through the input collection and append each node to its target container :
SQL> declare
2
3 type t_emp_tab is table of scott.emp%rowtype;
4
5 emp_tab t_emp_tab;
6 emp_info_xml xmltype;
7 emp_xml xmltype;
8
9 begin
10
11 -- filling emp_tab with data
12 select e.*
13 bulk collect into emp_tab
14 from scott.emp e
15 where e.deptno = 10;
16
17 emp_info_xml := xmltype('<EmpInfo/>');
18
19 -- looping through emp collection and appending to EmpInfo element
20 for i in 1 .. emp_tab.count loop
21 select appendchildxml(
22 emp_info_xml
23 , '/*'
24 , xmlelement("Emp"
25 , xmlattributes(emp_tab(i).empno as "id")
26 , xmlforest(
27 emp_tab(i).ename as "Name"
28 , emp_tab(i).job as "Job"
29 )
30 )
31 )
32 into emp_info_xml
33 from dual;
34 end loop;
35
36 dbms_output.put_line(emp_info_xml.getclobval(1,2));
37
38 end;
39 /
<EmpInfo>
<Emp id="7782">
<Name>CLARK</Name>
<Job>MANAGER</Job>
</Emp>
<Emp id="7839">
<Name>KING</Name>
<Job>PRESIDENT</Job>
</Emp>
<Emp id="7934">
<Name>MILLER</Name>
<Job>CLERK</Job>
</Emp>
</EmpInfo>
PL/SQL procedure successfully completed
2) Build a secondary collection of XML nodes and use XMLAgg to aggregate them in one go :
SQL> declare
2
3 type t_emp_tab is table of scott.emp%rowtype;
4
5 emp_tab t_emp_tab;
6 emp_info_xml xmltype;
7 emp_xml_tab xmlsequencetype := xmlsequencetype();
8
9 begin
10
11 -- filling emp_tab with data
12 select e.*
13 bulk collect into emp_tab
14 from scott.emp e
15 where e.deptno = 10;
16
17 -- looping through emp collection and appending to the collection of Emp nodes
18 for i in 1 .. emp_tab.count loop
19
20 emp_xml_tab.extend;
21
22 select xmlelement("Emp"
23 , xmlattributes(emp_tab(i).empno as "id")
24 , xmlforest(
25 emp_tab(i).ename as "Name"
26 , emp_tab(i).job as "Job"
27 )
28 )
29 into emp_xml_tab(i)
30 from dual;
31
32 end loop;
33
34 select xmlelement("EmpInfo", xmlagg(t.column_value))
35 into emp_info_xml
36 from table(emp_xml_tab) t ;
37
38 dbms_output.put_line(emp_info_xml.getclobval(1,2));
39
40 end;
41 /
<EmpInfo>
<Emp id="7782">
<Name>CLARK</Name>
<Job>MANAGER</Job>
</Emp>
<Emp id="7839">
<Name>KING</Name>
<Job>PRESIDENT</Job>
</Emp>
<Emp id="7934">
<Name>MILLER</Name>
<Job>CLERK</Job>
</Emp>
</EmpInfo>
PL/SQL procedure successfully completed
Both solutions give the same output.
Test them both and see which one fits better into your scenario. -
For-loop & iterator.remove()
Is it possible to remove an item during iterating with for-loop?
for (SelectionKey opKey : selector.selectedKeys())
// I need to remove opKey from selectedKeys set.
}Is it really necessary to remove handled key from selectedKeys set? What will happen if I run selector.select() while selectedKeys set contains some keys?Desiderata wrote:
Is it possible to remove an item during iterating with enhanced-for-loop?No
Is it really necessary to remove handled key from selectedKeys set? What will happen if I run selector.select() while selectedKeys set contains some keys?[Selector Selection|http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/Selector.html#selop] -
How to insert elements into an array after each iteration of a for loop
I am new to labview and working on an application where I am supposed to store an element into an array (without overwriting) after each iteration in a for loop. I have tried using Build Array Function keeping the indicator outside the for loop and played with indexing but didn't work. Please suggest me an idea how to do it.
Thanks
Solved!
Go to Solution.Thank you for your suggestion.Here is my actual application attached . In the first image, a difference in time is evaluated and an enum const of insert into array is passed to the shift register where it takes to Insert element into array phase (Second image). I need to enter the time difference into an array after every loop iteration. Please have a look and could you let me know where I am mislead.
Attachments:
Image 1.JPG 88 KB
Image 2.JPG 71 KB -
the demand of my application is that i can not replace for loop with a while loop.because i need fixed number of iterations and as far as i know fixed iterations could be only with possible with the for loop.
your recommended second option that i could add true/false case.
this true/false case must be inside the for loop or outside the for loop?if this case is inside the for
loop, how can i send stop command from outer while
loop?
more over do you have any example for this please?
thanks"You can execute a fixed number of iterations using a while loop by comparing the iteration count to the number of iterations you want and wiring the output of that comparison (e.g. Less Than or Equal To) to the continue (or stop) terminal of your while loop. Which comparison you use depends on personal preference, where you wire the desired count and the interation count, and whether you're using the while loop as Continue if True or Stop if True.
Ben gave you step-by-step instructions in response to your previous question. Look here for Ben's response.
Ben's response looks pretty good and detailed to me. It certa
inly deserved better than a 1-star rating.
Maybe you are looking for
-
Excise invoice not capturing during migo?
when I tried to capture the excise invoice during Migo. I am unable to select the capture only option. it is automatically selecting "refer only excise invoice"? how to solve this problem.
-
Word-by-word sort order in indexes
Hi again, I need to change the sort order in my indexes from letter-by-letter to word-by word. According to the help file, 1. Choose View > Reference Pages, and display the reference page that contains the special text flow for the index. 2. Add a sp
-
ITunes crashing... imagine that
Since ver 6.5... I have had nothing but issues. I tunes will crash out of no where and ask to send an error report or ITunes won't even open. With ver 7.1 I am still havig the crash and non opening issue but when it does open it asks if I want Itunes
-
Hi, How to change the vendor Name in SAP after saving the PO. Please help me on this. Regards S.Prasad
-
How do you convert into .pdf without the image name being show when cursor is on image (in pdf file)? thnx