开发者

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 w开发者_运维问答e 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.


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.


I don't think there is a noticeable difference. When you will access them, the two of them will be just 2 String arrays, so...


Making an array final does not make its elements final. That's one of the shortcomings of Java compared to C++. The only practical effect would be with optimizers and obfuscators. With what you describe, I'm pretty sure there will be no noticeable difference.


I believe you can mark a keyword as static or final if you assign it in the constructor. So just make sure that you read the file in the constructor of the static class. (I'm not 100% sure that Java has static constructors though, in C# this works, and both are often very alike).

Even if you can't do this trick I would still go with reading the 10k file. Reading a string[] is never going to be really expensive. And any optimization tricks that a compiler would normally do with a member marked as final can be done at runtime by the Java JITTER once it notices that the string[] is never changed anymore.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜