Skynet
Skynet

Reputation: 657

Constants concatenation in Java

If I have constants as

public static final String PREFIX = "meter.";

public static final String READING = "reading";

public static final String LEVEL = "level";

and I have a code which is

run() {
dao.set("meter.reading", x);
dao.set("meter.level", y);
}

Given that run() will be called millions of times a day,

would writing the above code as below degrade my performance due to the concatenation ? I would like to maintain constants separated from prefix as they are used with and without prefix in various context

run() {
dao.set(PREFIX+READING, x);
dao.set(PREFIX+LEVEL, y);
}

Upvotes: 1

Views: 950

Answers (4)

Elliott Frisch
Elliott Frisch

Reputation: 201439

I think it'll be optimized and in the String intern cache, and it'll use StringBuilder (depending on your jDK, in older JDKs it would have used StringBuffer) to construct that cached copy once. On my system this prints true and then true, notice that I'm correctly using '==' on two Strings in this test. Because these strings are all references to the same cached String.

public static final String PREFIX = "meter.";
public static final String READING = "reading";
public static final String C = PREFIX + READING;

public static void main(String[] args) {
  String a = PREFIX + READING;
  {
    String b = PREFIX + READING;
    System.out.println(a == b);
    System.out.println(a == C);
  }
}

Upvotes: 0

Ross Drew
Ross Drew

Reputation: 8246

I thought there was a tiny performance impact but apparently, I was wrong. Why not just

public static final String PREFIX = "meter.";

public static final String READING = PREFIX + "reading";

public static final String LEVEL = PREFIX + "level";

Upvotes: 0

rgettman
rgettman

Reputation: 178263

That will not degrade performance, because you are using compile-time constant expressions.

PREFIX+READING

The compiler will concatenate it for you, and it will be the same performance as the string literals you've tried.

The JLS, Section 15.28, defines constant expressions:

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

(other options)

  • The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3, §15.15.4, §15.15.5, §15.15.6)

(other options)

  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

(other options)

Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.

Upvotes: 7

Chris Chambers
Chris Chambers

Reputation: 1365

Strings are immutable, so it has to make a new string object every time you call run(). It's a simple operation, and I doubt you will have any trouble with it since you are not working with giant strings and high performance applications.

You should be fine.

Upvotes: -1

Related Questions