Skip to content

Conversation

@stsypanov
Copy link
Contributor

Assignment of default values to fields in general case is redundant, because the value will be there according to JLS. However in case of volatile field there is also performance issue, consider benchmark

@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(value = Mode.AverageTime)
@Fork(jvmArgsAppend = {"-Xms4g", "-Xmx4g"})
public class VolatileFieldBenchmark  {
  @Benchmark
  public Object explicitInit() {
    return new Class1();
  }
  @Benchmark
  public Object noInit() {
    return new Class2();
  }
  private static class Class1 {
    private volatile boolean field = false;
    public boolean isField() {
      return field;
    }
    public void setField(boolean field) {
      this.field = field;
    }
  }
  private static class Class2 {
    private volatile boolean field;
    public boolean isField() {
      return field;
    }
    public void setField(boolean field) {
      this.field = field;
    }
  }
}

The benchmark demonstrates that instantiation of a class without default value assignment takes less time:

Benchmark                            Mode  Cnt   Score   Error  Units
VolatileFieldBenchmark.explicitInit  avgt   40  11.087 ± 0.140  ns/op
VolatileFieldBenchmark.noInit        avgt   40   3.367 ± 0.131  ns/op

@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Jun 17, 2020
@jhoeller jhoeller self-assigned this Jun 17, 2020
@jhoeller jhoeller added in: core Issues in core modules (aop, beans, core, context, expression) type: task A general task and removed status: waiting-for-triage An issue we've not yet triaged or decided on labels Jun 17, 2020
@jhoeller jhoeller added this to the 5.3 M1 milestone Jun 17, 2020
@jhoeller jhoeller merged commit 7949937 into spring-projects:master Jun 17, 2020
@jhoeller
Copy link
Contributor

Well spotted, a good general rule to follow! Thanks for raising this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

in: core Issues in core modules (aop, beans, core, context, expression) type: task A general task

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants