0

I am writing a program and I am concerned about the time it takes to run and the space it takes.

In the program I used a variable to store the length of an array:

int len=newarray3.length;

Now, I wanted to know that whether I will be able to reduce the space complexity by not using the len variable and instead call the newarray3.length; whenever need.

Note: There are only two occasions when the length needs to be used.

drew moore
  • 31,565
  • 17
  • 75
  • 112
Biman Ghosh
  • 113
  • 7
  • 8
    You're barking up the wrong tree. If your program is slow, you need to profile it to find out what's taking the most time, guessing is rarely intuitive. – Evan Trimboli Apr 07 '13 at 21:21
  • 1
    Hint: `newarray3.length` is already a simple field. Not a method call to some heavy duty function. – Mysticial Apr 07 '13 at 21:21
  • Calling `length` on an array should be constant time, as explained in this SO post: http://stackoverflow.com/questions/1208320/what-is-the-cost-of-calling-array-length So if constant time is enough to be a performance issue for you, you're probably looking at the wrong issue as @EvanTrimboli is pointing out. – Darwind Apr 07 '13 at 21:24

3 Answers3

8

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" - Donald Knuth

First off, a single int variable uses a negligible amount of space. More generally, don't worry about these minor performance ("time and space") issues. Focus on writing clear, readable programs and efficient algorithms. If performance becomes an issue down the line, you'll be able to optimize then as long as your general architecture is solid. So focus on that architecture.

drew moore
  • 31,565
  • 17
  • 75
  • 112
0

I really doubt that this is the thing that will improve your performance. Anyway, I would use newarray3.length (instead of assigning to a new variable which takes memory and adds another operation). This is a field anyway (not even a method call). Reading it is the same as reading the int value you copied but you spare the copying and the 4 bytes of memory that int consumes.

Avi
  • 21,182
  • 26
  • 82
  • 121
0

Java arrays are not resizable so the length member variable is constant for that object, this can lead to various optimizations by JIT.

Nándor Krácser
  • 1,128
  • 8
  • 13