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.
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).