Thread: can this code be optimised? to be faster ?

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    5

    can this code be optimised? to be faster ?

    Code:
      public int Add(object value)        {
    
    
                object[] tmp = new object[_items.Length + 1];
    
    
    
    
                for (int i = 0; i < _items.Length; i++)
                {
                    tmp[i] = _items[i];
                }
    
    
    
    
                tmp[tmp.Length - 1] = value;
    
    
    
    
                _items = tmp;
                return tmp.Length - 1;
            }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    "Array.Resize()" might be faster than your loop.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Nov 2015
    Posts
    5
    i want to implement Ilist method Add(object value) not resize how do you think if i do in one for loop will it be faster than this?

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Quote Originally Posted by badger777 View Post
    i want to implement Ilist method Add(object value) not resize
    But that's what you're doing in this method, isn't it? You create a new, longer array, copy the old elements to it and add a new one at the end. Array.Resize() can do the first two steps for you.
    Devoted my life to programming...

  5. #5
    Registered User
    Join Date
    Nov 2015
    Posts
    5
    can you show me how can it be done? your version

  6. #6
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Maybe you should forget about speed optimization until you are comfortable with the language...
    Devoted my life to programming...

  7. #7
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Why aren't you just using a List<object> instead of an array, which already does what you're trying to do?
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Faster code
    By Aslaville in forum C++ Programming
    Replies: 15
    Last Post: 10-19-2014, 12:07 PM
  2. Replies: 10
    Last Post: 02-28-2012, 02:12 AM
  3. Why this loop is not optimised out?
    By jgo in forum C Programming
    Replies: 7
    Last Post: 10-06-2011, 03:07 PM
  4. Which is faster?
    By Yarin in forum C++ Programming
    Replies: 10
    Last Post: 02-05-2008, 09:50 AM
  5. Trying to make this code faster & Cramer
    By just2peachy in forum C++ Programming
    Replies: 3
    Last Post: 12-03-2004, 10:54 AM

Tags for this Thread