Object creatation in loops

How expensive are this calls and is there maybe a better way
I would like to print a second after the epoch in a human redable way like with date.toString();
int[] secondsAfterEpoch = ....;
for (int i = o ; i < secondsAfterEpoch ; i++) {
out.println(new Date((long)secondsAfterEpoch[i] * 1000).toString());
very inefficient? better way?
Thanks for any ideas.

Object instantiation is not really expensive.
If you want more performance, you might want to assemble the string yourself using a StringBuffer and a Calendar (needs to change only once every 86400 iterations), and calculating the hours minutes and seconds from your i. Or Maybe a new Date() only once a day to catch the date part of the String.
Much simpler to do a stupid division that the entire formatting process for each iteration.

Similar Messages

  • Creating objects in a loop

    Hi
    I have read that creating objects in a loop degrades performance. Can someone explain why this should be so?

    Hi
    I have read that creating objects in a loop degrades
    performance. Can someone explain why this should be
    so?Every object creation takes time, so if you create
    lot of unnecessary temporary items in loop it degrades
    performance (so it is nothing loop specific).

  • Multiple objects created in loop

    How do I create multiple objects for the same class with a loop
    I can hard code the names in but I want to allocate names from an array as the names
    ie
    BankAccount Acct(NameArray[0]) = new BankAccount();
    to get
    AcctFred.method();
    and access this in a loop
    I know if can be done but how??
    Regards, Cat

    Another variation:
       String[] names = { "Peter", "John", "Suzie" };
       // Creates the accounts and stores them in the hash table
       HashTable hAccounts = new HashTable();
       for (int i = 0; i < names.length; i++) {
          BankAccount account = new BankAccount(names);
    hAccounts.put(names[i], account);
    // Retrieves an account by its name
    Account account = (Account)hAccounts.get("John");
    Hope this helped,
    Regards.

  • Populating an array of objects with a loop. Noob PHP question.

    Hey guys,
       You are all such a great help! Here is another one for you, the simple code below should create an array of pizza objects (and it does) then display each object in order. However... for some reason each object in the array seems to inherit the properties of whatever the last object entered was.
    This code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>
    <?php
    class pizza{
              public $price;
              public $description;
              public $name;
    $menu2=fopen("pizzaMenu2.txt","r") or exit("System Error!");
    $pizzas = array();
    $arraypos=0;
    //This loop does all of the READING and populating of variables
    while(!feof($menu2))
                //First get the array position
                                  $arraypos = (int)fgets($menu2);
              //Then Put in Title in title2 array
                                  $pizzas[$arraypos2] = new pizza(0,0,0);
                                  $pizzas[$arraypos2]->title = fgets($menu2);
                                  $pizzas[$arraypos2]->description = fgets($menu2);
                                  $pizzas[$arraypos2]->price = fgets($menu2);
      } //End of reading loop
    //begin writing data
    $arraypos=1;
    while ($arraypos <=3){
              echo "the array is in position: ".$arraypos;
              echo "<br />";
              echo $pizzas[$arraypos2]->title;
              echo "<br />";
              echo $pizzas[$arraypos2]->description;
              echo "<br />";
              echo $pizzas[$arraypos2]->price;
              echo "<br />";
              $arraypos++;
    }//end of writing data loop
    fclose($menu2);
    ?>
    <body>
    </body>
    </html>
    returns this:
    the array is in position: 1
    Test Pizza Two
    The same as one with an extra one, yum!
    22.99
    the array is in position: 2
    Test Pizza Two
    The same as one with an extra one, yum!
    22.99
    the array is in position: 3
    Test Pizza Two
    The same as one with an extra one, yum!
    22.99
    when it should return this:
    the array is in position: 1
    Test pizza One
    Loaded with all that test pizza goodness! Lots and lots of ones 1111!
    11.99
    the array is in position: 2
    Test Pizza Two
    The same as one with an extra one, yum!
    22.99
    the array is in position: 3
    Test Threeza!
    Do you see what I did there? I added a three to pizza, hahaha, I am so punny.
    33.33
    using the following text file pizzaMenu2.txt:
    1
    Test pizza One
    Loaded with all that test pizza goodness! Lots and lots of ones 1111!
    11.99
    3
    Test Threeza!
    Do you see what I did there? I added a three to pizza, hahaha, I am so punny.
    33.33
    2
    Test Pizza Two
    The same as one with an extra one, yum!
    22.99
    Now, I have done line by line testing and shown that the values are being entered into the proper objects in the proper array, but whatever goes in last overwrites all of the other objects, so in the end I have 3 objects in my array that are all the same. I am not sure what I am missing here.

    Christ-Guard wrote:
    Thanks! I majored in computer science
    That helps enormously.
    Christ-Guard wrote:
    Also, I have never worked a CS job before and I've been out of school for 8 years, so I am better at remembering "This should work" then I am at "This is how I write this code".
    If you have a good idea something should work, based on theory, then that's half the battle.
    Its having no knowledge if something will work or not when it becomes a problem.

  • SSIS 2008 R2 Foreach Loop Container on ADO object in Endless Loop

    SSIS 2008 R2
    I have an object Variable populated by a SQL Query.  I then attach it to a Foreach Loop Container with "Foreach ADO Enumerator" and define the variable mappings.  Inside the Foreach Loop is a series of tasks.  It appears that the
    tasks are processing each of the rows in the Object but it also appears that the Foreach loop never stops but runs until I kill it.  I was under the impression that the Foreach loop would stop when after the last row in the Object was consumed. 
    As it is now, the Foreach Loop is useless as it runs forever. 
    Any suggestions would be appreciated.
    Thanks,
    Michael
    P.S.   I have determined that the ADO object has a size or count limitation which if exceeded causes the Foreach Loop task to malfunction in both Studio and as an Agent job.  I could not find a limit in MS docs, but there sure seems to be
    a limit somewhere which everyone should be aware of.  5,000 rows exceeds the limit, in my case.

    A typical memory limit rather, especially noticeable in dev env where it is 32 bit
    http://www.codeguru.com/csharp/.net/article.php/c16921/Understanding-NET-application-options-for-32-and-64bit-systems.htm
    Arthur My Blog

  • How to re-establish a C++ object through a loop of C++/Java/C++ ?

    Hi, there:
    My problem is a bit awkward. My application has two JNI components,
    handling different aspects of low level computation. Each of the JNI
    wraps up a C++ library with the java version APIs. The java code
    calls one JNI to establish an object corresponding to a C++ class.
    Then after some manipulation, I need to go back to C/C++ level to
    use this object to do more low level work using the second JNI.
    How can I put the jobject back to a C++ object, so that I can call
    the C++ APIs of the first C++ library directly from my second JNI
    and avoid go through the wrapped java APIs?
    Hopefully, I didn't ask something obvious. Thanks.
    Ligg

    I wouldn't know about using JVM data copying operations to solve this problem. Because of my ignorance, it sounds just plain scary.
    However:
    o You are calling your first dll from java. That tells me that you have somehow defined a subroutine with C linkage. That subroutine ought to be able to grab the C++ object in question, and store the address in a globally-defined pointer.
    o It sounds like the second dll knows about the C++ object definition from the first dll. (Otherwise it would make no sense trying to pass to it an object of the sort you mention.) So it sounds like the second dll ought to be able to declare that an external pointer exists to this desireable C++ object, and the loadLibrary call on the second dll ought to fill in the appropriate linkage for you - resolving the addresses.
    I say "ought to". I haven't tried this, although in C I have certainly used external linkages before and let loaders do the fixup.

  • Multiple object creation in a loop

    I want to create lots of objects in a loop, but I cannot figure out how to substitute an array into the code. So, I was hoping to use Rectangle rect[i] instead of Rectangle rectOne, where i is my counter. Assuming this is a reasonable method, where can I track down the syntax?
    Rectangle rectOne = new Rectangle(originOne, 100, 200);
    Rectangle rectTwo = new Rectangle(50, 100);

    Something still isn't quite right. I made up some simpler code to get to the answer, if it is helpful, the actual code is below. This code is supposed to read a text file and pull in tab delimited data. At the commented line, it breaks, expecting a semi but finding 'aa'. I can get this to work if I don't use an array (so, 'aa' is overwritten each time the loop runs, instead of aa[i] which would contain all of the values). Unfortunately, I have to refer back to the individual Nodes ('aa') in later code and can't if the values have been overwritten. I'm trying to keep my code simple, if I'm not asking the question correctly, or if you need more information, please let me know.
    void setup() {
      String[] lines;
      lines = loadStrings("Product Migration.txt");
      for (int i = 1; i < lines.length; i++) {
        String[] pieces = split(lines, '\t');
    Node[] aa = new Node[5];
    for (int j = 0; j < pieces.length; j++) {
    String[] tempArray = new String[lines.length];
    Node aa[i] = new Node(this, pieces[j], j * 75 + border, i * 50); // code breaks in compiler here.
    net.addNode(aa);
    Edited by: LouisvilleLIP on Jun 11, 2008 4:40 AM
    Edited by: LouisvilleLIP on Jun 11, 2008 4:41 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Select-option in ABAP objects

    Hi Guys,
               I need a small help from you. I want to know how to populate the value from select-option to abap object. Please help me, it is very important

    check this code
    REPORT ZSELOPT_TO_CLASS .
    TABLES: VBRK.
    SELECT-OPTIONS: S_VBELN FOR VBRK-VBELN.
    DATA: IT_VBELN TYPE RSELOPTION.
    DATA: X_VBELN TYPE RSDSSELOPT.
    CLASS C1 DEFINITION.
    PUBLIC SECTION.
    DATA: IT_VBRP TYPE VBRP_TAB,
          X_VBRP LIKE LINE OF IT_VBRP.
    METHODS: GET_DATA IMPORTING S_VBELN TYPE RSELOPTION.
    METHODS: DISP_DATA.
    ENDCLASS.
    CLASS C1 IMPLEMENTATION.
    METHOD GET_DATA.
      *SELECT * FROM VBRP*
       INTO TABLE IT_VBRP
       WHERE VBELN IN S_VBELN.
    ENDMETHOD.
    METHOD DISP_DATA.
      LOOP AT IT_VBRP INTO X_VBRP.
        WRITE:/ X_VBRP-VBELN,
                X_VBRP-POSNR.
      ENDLOOP.
    ENDMETHOD.
    ENDCLASS.
    START-OF-SELECTION.
    DATA OBJ TYPE REF TO ZCL_SELOPT.
    CREATE OBJECT OBJ.
    LOOP AT S_VBELN.
      MOVE S_VBELN-LOW TO X_VBELN-LOW.
      MOVE S_VBELN-HIGH TO X_VBELN-HIGH.
      MOVE S_VBELN-SIGN TO X_VBELN-SIGN.
      MOVE S_VBELN-OPTION TO X_VBELN-OPTION.
      APPEND X_VBELN TO IT_VBELN.
    ENDLOOP.
    CALL METHOD OBJ->GET_DATA
                        EXPORTING
                          S_VBELN = IT_VBELN.
    CALL METHOD OBJ->DISP_DATA.
    Edited by: moazam hai on May 17, 2008 6:17 AM
    Edited by: moazam hai on May 17, 2008 6:19 AM

  • Multiple instantiations of the same object

    Can someone please explain to me the difference of these two circumstances upon the JVM:
    1) I declare an object outside the loop and instantiate a new object on each iteration of the loop
    Object obj = null;
    for (int i = 0; i < 6; i++) {
        obj = new Object();
    }2) I declare and instantiate the object inside the loop only
    for (int i = 0; i < 6; i++) {
        Object obj = new Object();
    }I assume in the first example that I am reserving memory space and overwriting it on each iteration, whereas in the second example I am reserving and consuming a new memory space on each iteration.
    If that assumption is correct, which is the more efficient? Wouldn't option 1 be easier on garbage collection?

    I compiled both cases using Sun javac (1.4.1) and used javap to view the compiled code. It looks the same to me. Here's the compiled code (for the loop) for the first case   2 iconst_0
       3 istore_2
       4 goto 18
       7 new #2 <Class java.lang.Object>
      10 dup
      11 invokespecial #1 <Method java.lang.Object()>
      14 astore_1
      15 iinc 2 1
      18 iload_2
      19 bipush 6
      21 if_icmplt 7
      24 returnHere's the compiled code the second case   0 iconst_0
       1 istore_1
       2 goto 16
       5 new #2 <Class java.lang.Object>
       8 dup
       9 invokespecial #1 <Method java.lang.Object()>
      12 astore_2
      13 iinc 1 1
      16 iload_1
      17 bipush 6
      19 if_icmplt 5
      22 return

  • Dynamically instantiating objects using string name

    Hello to all.
    This is probably an easy question, but I am wondering how I can dynamically create instances of an object in a loop using a string variable as the name.
    The idea here is this:
                   while (someBooleanVariable) {
                        int count = 1;
    String objectName = "myObject" + count;
                        myObject objectName = new myObject; // How do I pass the objectName String variable as a name?
                        count++;
                   } // End while
    Of course this doesn't work - incompatible types, but the idea is that the code would create "myObject1," "myObject2," "myObject3," "myObject4," etc as long as someBooleanVariable = true using the objectName String variable.
    I am new to this and appreciate any help and ideas.
    Thanks!

    BigDaddyLoveHandles wrote:
    There's been this outbreak of people wanting to dynamically name their variables -- is this some sort of scripting disease?It's always been around. Shoot, I remember suffering from it when I first started out, because it seems so, hm I dunno, necessary at the time. Eventually the newbie (me) realizes that the variable "name" means nothing, that reference is everything.
    ... and then I discovered maps, and names were useful again. :o)

  • Invalid table name  error when updating object in collection using SQL

    Hi,
    I have pl/sql code where I am selecting a object from a collection using sql select query. I am processing this record and now I want to update the collection with the new object. ie. ensure that the object that was fetched be removed and this new one be added.
    considering my_ot is the object type and my_tt is the table type.
    DECLARE
    my_col my_tt;
    my_col1 my_tt
    my_var my_ot;
    my_var2 VARCHAR2(10);
    BEGIN
    // populating my_col1 with select query
    //populating my_col with select query
    FOR my_col1.FIRST .. my_col.LAST LOOP
    //populating my_var2
    BEGIN
    SELECT my_ot(c.field1, c.field2 ,c.field3) INTO my_var FROM TABLE(my_col) c WHERE c.field3 = my_var2
    //processing the field my_VAR
    UPDATE TABLE(my_col) c SET c.field1 = my_var.field1 , c.field2 = my_var.field2 , WHERE c.field3 = my_var.field3;
    EXCEPTION WHEN NO_DATA_FOUND
    my_col.EXTEND;
    my_col(my_col.LAST) := // new my_ot object
    END;
    END LOOP;
    Here, when compiling the update query is not being compiled. I am getting a error 'invalid table name'. Is there any way to modify an object in the collection without knowing its index?
    If not, is it possible to find the index of a object in the collection in select query?
    Thanks in advance
    Paddy

    Hi,
    Is there any way to find the index of a object in the collection? Then I will simply replace the object at that index, right!
    Thanks
    Paddy

  • Placing an array of objects onto stage

    I am trying to place an array of objects onto a stage where they drop vertically. I have been able to do it by placing the array objects into an object called "bag" but have found that the bag object only contains the last array object id so I can not apply actions to various array objects.
    Also my objects do not loop and only appear once.
    Below is the code so far.
    var tempArray:Array = new Array(); // Stores randomised values
    var bagArray:Array = new Array("gslow_id","gshigh_id","glow_id","ghigh_id","gdiv_id",
      "gcall_id","gbust_id","gbull_id","gboom_id","gbear_id"); // List of bag names
    function createBags() {
    if (tempArray.length == 0) { // check if array is empty
         for (var i:Number = 0; i < targets; i++) { // for loop - creat variable bagName to the value of targets
         var bagName: String = bagArray[i];
         var depthLevel:Number = this.getNextHighestDepth();
         // attach movies to time line
         this.attachMovie(bagName, bagName, depthLevel, {_x:random(350) + 100, _y:random(0) + spacing});
         spacing += 45;
         tempArray.push(bagName);
         //trace(tempArray);
         bag = _root[bagName]; // create a bag object contain the bagName variable
         //trace (bag);
         bag.onEnterFrame = function() {
              if (this._x < 570 && this._y > 0) {
              this._y += speed * random(8);
              } else {
              this._x = random(500);
              } // end if (this._x < 570 && this._y > 0)
         } // end bag.onEnterFrame ()
    bag.onPress = function() {
    // if bag is pressed select action
    //trace (bag); 
    xPos = this._x
    yPos = this._y
    unloadMovie(this);
    score += 1000
    scoreText_txt.text = score;
    //trace(score);
    checkScore();
    } // end bag.onPress ()
    //trace(targets);
    //trace(bagName);
    } // end for (var i:Number = 0; i < targets; i++)
    } // end if (tempArray.length == 0)
    } // End createBags()

    try:
    var bagA:Array=[];
    var bagArray:Array = new Array("gslow_id","gshigh_id","glow_id","ghigh_id","gdiv_id",
      "gcall_id","gbust_id","gbull_id","gboom_id","gbear_id"); // List of bag names
    function createBags() {
    if (tempArray.length == 0) { // check if array is empty
         for (var i:Number = 0; i < targets; i++) { // for loop - creat variable bagName to the value of targets
         var bagName: String = bagArray[i];
         var depthLevel:Number = this.getNextHighestDepth();
         // attach movies to time line
         var bag:MovieClip = this.attachMovie(bagName, bagName, depthLevel, {_x:random(350) + 100, _y:random(0) + spacing});
      bagA.push(bag);
         spacing += 45;
         //trace (bag);
         bag.onEnterFrame = function() {
              if (this._x < 570 && this._y > 0) {
              this._y += speed * random(8);
              } else {
              this._x = random(500);
              } // end if (this._x < 570 && this._y > 0)
         } // end bag.onEnterFrame ()
    bag.onPress = function() {
    // if bag is pressed select action
    //trace (bag); 
    xPos = this._x
    yPos = this._y
    unloadMovie(this);
    score += 1000
    scoreText_txt.text = score;
    //trace(score);
    checkScore();
    } // end bag.onPress ()
    //trace(targets);
    //trace(bagName);
    } // end for (var i:Number = 0; i < targets; i++)
    } // end if (tempArray.length == 0)
    } // End createBags()

  • Perl API: growing memory problem in loops over large sets of data

    Hi,
    When going through all XmlResults like this:
    while ($results->next($val)) {
    print $val->asString, "\n";
    The process size keeps growing. It does not when I comment $val->asString method out, but then I have no way of getting the results.
    This becomes a significant problem when the number of results is huge. I am doing this on a database of over a million short XML documents (400-800 bytes each).
    The more complete code is here:
    eval {
    $env = new DbEnv();
    $env->open($dbDir, Db::DB_JOINENV | Db::DB_INIT_LOCK
    | Db::DB_INIT_MPOOL | Db::DB_CREATE, 0);
    my $mgr = new XmlManager($env, DbXml::DBXML_ADOPT_DBENV);
    my $db = $mgr->openContainer(undef, $dbName, Db::DB_RDONLY);
    my $context = $mgr->createQueryContext(XmlQueryContext::LiveValues,
    XmlQueryContext::Lazy);
    my $lookup = $mgr->createIndexLookup($db, "", $nodeName,
    "node-$nodeType-equality-$syntax",
    new XmlValue($types{$nodeType}, $value), XmlIndexLookup::GTE);
    my $results = $lookup->execute(undef, $context);
    my $val = new XmlValue();
    while ($results->next($val)) {
    print $val->asString, "\n";
    if (my $e = catch std::exception) {
    die $e->what() . "\n";
    The process size just grows until the system limit is reached, then the process quits saying 'Out of memory'.
    I suspect the problem is with the std::string result returned by C++ XmlValue::asString() const.
    The (left-hand-side) result string is likely allocated by new std::string and receives the value by calling the string copy operator. Then the Perl scalar result is prepared, but when it gets returned to my code, the C++ string is not deleted.
    Moving the Sleepycat::XmlValue Perl object inside the loop does not help either:
    while ($results->hasNext()) {
    my $val = new XmlValue();
    $results->next($val);
    print $val->asString, "\n";
    In fact, the process seems to grow faster, possibly because the old $val instances do not get destroyed by Perl at the end of the loop. Where is Perl's garbage collection?
    I am using DB XML version: 2.2.13; BDB version: 4.4.20.2; OS: FreeBSD 6-STABLE. However the problem seems to be common for any OS or BDB XML version as it involves Perl-to-C++ interface.
    Has anyone experienced similar problems?
    Thanks,
    Konstantin.
    Konstantin @ Chuguev.com

    Good catch - you found a memory leak. Luckily the fix is very straightforward. Edit the file
    dbxml/src/perl/common.h
    and find this line
    #define newSVfromString(str) newSVpvn(str.c_str(), str.length())
    Change it to this
    #define newSVfromString(str) sv_2mortal(newSVpvn(str.c_str(), str.length()))
    and recompile the module.
    Paul

  • Creating objects in a second instance

    I have created a second instance through the console of a directory server, which has been configured with the same rootdn as the original.
    When I open up the console why in the new instance does it show the rootdn on the config tab but the original doesnt ......
    also ....
    why when i go into the second instance i try creating data objects for root suffixes ive created to mirror the original instance, does it create them under cn=config ......
    Thanks
    G

    Hi
    I have read that creating objects in a loop degrades
    performance. Can someone explain why this should be
    so?Every object creation takes time, so if you create
    lot of unnecessary temporary items in loop it degrades
    performance (so it is nothing loop specific).

  • HELP dynamically call objects

    I'll try to explain this as best as possible...
    I have created an applet that has 30 check boxes. I have a button above the check box that reads sort alphabetically. When I click the button I would like the check boxes to sort themselves alphabetically by label. Here is where I'm running into trouble:
    I want to create a loop that basically sets each box y15 below the previous box. Here is what I have so far
    //nameList is a vector that stores the text in the labels
    //nameList is in alphabetical order
    int newYpos = 20;
         for(int x=0;x<nameList.size();x++){
              //set absent box
              ivjJCheckBox0.setBounds(144, newYpos, 15, 22);
    newYpos += 15;
    MY PROBLEM: each box is named ivjJCheckBox0 through ivjJCheckBox29
    I need to call each box incrementally. The long and absent minded way would be to create 60 lines of code that basically did the following:
              ivjJCheckBox0.setBounds(144, newYpos, 15, 22);
    newYpos += 15;
              ivjJCheckBox1.setBounds(144, newYpos, 15, 22);
    newYpos += 15;
              ivjJCheckBox2.setBounds(144, newYpos, 15, 22);
    newYpos += 15;
    MY QUESTION: How can I call each individual object in a loop?

    So why didn't you just use an array of checkboxes? And why didn't you use a layout manager? Either of those two things would have made your task much easier.

Maybe you are looking for

  • Error message when trying to finalize project in iMovie

    I get the following message when I attempt to finalize my project in iMovie: "The project could not be prepared for publishing because an error occurred. (OpWrErr: file already open with with write permission)" This message appears well into the 6 or

  • Macbook pro with monitor VS imac with ipad

    Hello and thanks for helping me out! I have an older MacBook Pro, via 2007.  It hasn't been updated, has the old processor, etc. I use it for storage of older pics and music now. Main focus: I am now much more into Photoshop CS5, do travel quite a bi

  • How to change writing language in E61i?

    I use both Arabic and English languages in my new E61i device. To change writing language while writing text, I can use the Writing Language option from the Options menu. But this option is not available in all cases in built-in applications, and doe

  • Best way to handle sounds in AS3

    I'm currently doing some game development, targeting iOS and Android devices using Flash Pro and AS3.  I'm doing my best to keep the code highly optomized and doing as much object pooling as possible. So far, I'm very pleased with how smooth everythi

  • Audio start playing unexpectedly when loaded in LMS

    Hi all, this is another strange issue i encountered. I inserted a video in one of my courses. During the preview stage (and after i publish to .swf to test locally), everything played smoothly. But when I uploaded it to the LMS, the audio from the vi