Lucas Lucas - 1 year ago 43
Java Question

Performance of using a variable for input handling?

To check a string input before using it, I often use code as shown in the first block. The second block does the same, but is there a difference in performance? (for example, is the textfield read twice in the first code block?) Also is one considered as bad coding or can I use both of them?

if (!textField.getText().equals("")) {
name = textField.getText();
}


or

String ipt = textField.getText();
if (!ipt.equals("")) {
name = ipt;

Answer Source

In terms of performance, the second is faster as it spares a duplicated processing.
But it is a so cheap task that you should execute it million times to see a difference.
Besides, modern JVMs performs many optimizations. Which could result in similar performance in both cases.

But in these two ways, I notice bad smells :

This way :

if (!textField.getText().equals("")) {
    name = textField.getText();
}

introduces duplication.
It is generally unadvised as if we forget to change the duplicate everywhere we may introduce issues.
Duplicating one line of code is often not a serious issue but generally textfields are not single. So you perform very probably this task for multiple textfields. Duplication becomes so a problem.

This way :

String ipt = textField.getText();
if (!ipt.equals("")) {
    name = ipt;

introduces a local variable that has a scope broader than required. It is also discouraged to make the code less error prone as we may reuse the variable after the processing where it is required while we should not be able to.
For your requirement, I dislike both solutions.

A better quality and efficient way would be introduce a method :

private String getValueOrDefault(TextField textField, String defaultValue) {
  String value = textField.getText();
  return !value.equals("") ? value : defaultValue;
}

You can invoke it in this way :

name = getValueOrDefault(textField, name);

You don't have any longer a variable that lives beyond its requirement and you don't have duplication either.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download