statisch vs. new performance

Heute hatten wir eine Diskussion darüber, ob auf einen Wert via einem statischen Klassenmember oder über einen Getter zugegriffen werden soll oder ob es sogar egal ist wenn man jedes Mal eine neue Instanz erzeugt. Jetzt hat es mich gejuckt, mal einfach ein kleines Beispiel zu machen. Mir ist klar, dass entscheidend ist, wie teuer das erzeugen des Objektes ist. Aber hier sind einfach mal die Zahlen vom Beispiel um ein Gefühl zu bekommen:

count: 10
static  msec: 0
get     msec: 0
new     msec: 0
count: 100
static  msec: 0
get     msec: 0
new     msec: 0
count: 1000
static  msec: 0
get     msec: 0
new     msec: 2
count: 10000
static  msec: 4
get     msec: 1
new     msec: 16
count: 100000
static  msec: 1
get     msec: 1
new     msec: 32
count: 1000000
static  msec: 0
get     msec: 0
new     msec: 224
count: 10000000
static  msec: 0
get     msec: 0
new     msec: 1848
count: 100000000
static  msec: 0
get     msec: 0
new     msec: 19029

Und hier noch das Beispiel:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Main {

    private static final Person PERSON = new Person();
    private static long timestamp;

    public static void main(String[] args) {
        int count = 10;
        for(int i = 1; i < 9; i++){
            System.out.println("count: " + count);
            iterate(count);
            count *= 10;
        }
    }

    private static void iterate(int count){
        timestamp = System.currentTimeMillis();
        iterateStatic(count);
        out("static ");
        timestamp = System.currentTimeMillis();
        iterateGetter(count);
        out("get    ");
        timestamp = System.currentTimeMillis();
        iterateNew(count);
        out("new    ");
    }

    private static Person getPerson(){
        return PERSON;
    }
    
    private static void iterateStatic(int count){
        for(int i = 0; i < count; i++){
            Person person = PERSON;
            person.blub();
        }
    }
    private static void iterateNew(int count){
        for(int i = 0; i < count; i++){
            Person person = new Person();
            person.blub();
        }
    }
    private static void iterateGetter(int count){
        for(int i = 0; i < count; i++){
            Person person = getPerson();
            person.blub();
        }
    }
    private static void out(String s){
        System.out.println(s + " msec: " + (System.currentTimeMillis()-timestamp));
    }
}

class Person {

    private Map aMap = new HashMap();
    private Set aSet = new HashSet();

    public Person() {
    }

    void blub(){
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s