Skip to content

Instantly share code, notes, and snippets.

@emopers
Created April 24, 2016 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emopers/f8797f547a0322df9e0e0c839bd5886f to your computer and use it in GitHub Desktop.
Save emopers/f8797f547a0322df9e0e0c839bd5886f to your computer and use it in GitHub Desktop.
Usefulness of property *_StaticFactory
We have seen large amount of violations for
{Boolean, Byte, Character, Double, Float, Long, Integer, Short}_StaticFactory properties during runtime monitoring.
However, we don't feel these properties very useful in monitoring most appplication programs.
Though it is stated in Java API (link: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28int%29)that using StaticFactory
"is likely to yield significantly better space and time performance by caching frequently requested values.",
we think that 1) these performance bugs are less concerned for common developers than functional bugs and
2) according to our experiment, using static factory seems not render better space and time performance, or even worse.
Following is the snippet we used for experiment:
import java.util.Random;
2
3public class TestStaticFactory {
4 public static void main(String[] args) {
5 long startTime = System.nanoTime();
6 Random r = new Random();
7 for(int i = 0; i < 1000000000; i++) {
8 int num = r.nextInt() % 1000;
9 Integer result = staticFactory(num);
10 }
11 long elapseTime = System.nanoTime() - startTime;
12 System.out.println(Runtime.getRuntime().maxMemory());
13 Runtime.getRuntime().gc();
14 System.out.println("static " + elapseTime);
15 startTime = System.nanoTime();
16 r = new Random();
17 for(int i = 0; i < 1000000000; i++) {
18 int num = r.nextInt() % 1000;
19 Integer result = nonStaticFactory(num);
20 }
21 elapseTime = System.nanoTime() - startTime;
22 System.out.println(Runtime.getRuntime().maxMemory());
23 System.out.println("non-static " + elapseTime);
24
25 }
26
27 private static Integer nonStaticFactory(int num) {
28 return new Integer(num);
29 }
30
31 private static Integer staticFactory(int num) {
32 return Integer.valueOf(num);
33 }
34}
With int within 1000 being processed 1 billion times, the caching effects of static factory should be significant.
However, static factory method seems to take at least 10% time overhead than non-static factory method and the same maximum memory usage.
The result is similar if change the code to call non-static factory method before static factory method.
In all, though these properties might be useful for high-performance computing,
we do not think these properties provide more benefits to common developers than the noise they introduce.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment