Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which of the two practices is more efficient in Java?

I have an object array, I know that the elements are type String, say I need to access them many times.

  • Practice 1: access the element by array index and cast it to String every time I need it.
  • Practice 2: create local String instances and access each of the elements once.

Which will run faster? If it's on a mobile device where memory is limited, which would be an over all better practice? Thank you.

like image 265
derrdji Avatar asked Nov 22 '25 09:11

derrdji


1 Answers

You're asking the wrong question. Don't optimize until you know what needs to be optimized. Instead, write the clearest, easiest to understand code you can, then refactor when you know there's an issue (and you've determined what the issue is).

In this case, I'd think it's a lot easier to just maintain an array and cast them to String as needed. If that turns out to be a problem, I'd refactor (possibly by creating a String array and copying the objects into that, once).

like image 67
Chris B. Avatar answered Nov 24 '25 21:11

Chris B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!