Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance accessing static final

I have a static 10K file with a word on each line. I need to create a String[] array with all the words. I have 2 options:

  1. I create a static final String[] words and hardcode by hand all the words in my code.
  2. At start-up, load the file, parse it and create a static String[] words array with all the words.

Now, my question is, after all this is done, is accesing a word from the array 1 (notice the final keyword) noticeably faster than a word from the array 2 (no final keyword because we load the words at runtime). Theoretically does it make a difference? And we're talking here about Android specifically, not Java. But I am interested in both cases.

like image 390
Catalin Morosan Avatar asked Dec 28 '25 01:12

Catalin Morosan


1 Answers

Generic Java:

There are no bytecodes for array initialization in the JVM, so the compiler ends up generating individual assignment statements for each array item, which bloats the code. See here for more information.

Loading the values from a file is the most efficient scenario given the amount of data you have. Whether the array is declared final or not is irrelevant, as the strings themselves are immutable.

Android:

The DVM improves on the JVM by adding instructions for initializing arrays. So you don't have the same code bloat issues.

That said, loading things from a file is likely the most flexible approach. Done properly, you could load values from multiple files if necessary, even across the Internet.

like image 181
Eric Giguere Avatar answered Dec 30 '25 15:12

Eric Giguere



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!