Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7533021
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T05:37:19+00:00 2026-05-30T05:37:19+00:00

Suppose I have a simple interface representing a complex number, whose instances would be

  • 0

Suppose I have a simple interface representing a complex number, whose instances would be immutable. For the sake of brevity, I omitted the obvious plus, minus, times and divide methods that would simply create and return a new immutable instance.

public interface Complex {

    double real();

    double imaginary();

    double absolute();

    double angle();

}

Now the question is, what would the best way to implement this as an immutable class? The most simple and straightforward “I care about performance only when it’s a problem” approach would be to store the real and imaginary parts as final fields and compute the absolute value and angle on every invocation of those methods. This keeps the class small and simple, but obviously the last two methods return the same result every time.

public final class NonCachingComplex implements Complex {

    private final double real;
    private final double imaginary;

    public NonCachingComplex(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    @Override public double real() {
        return real;
    }

    @Override public double imaginary() {
        return imaginary;
    }

    @Override public double absolute() {
        return Math.sqrt((real * real) + (imaginary * imaginary));
    }

    @Override public double angle() {
        return absolute() == 0 ? 0 : (Math.acos(real / absolute()) * Math.signum(imaginary));
    }
}

So why not save the absolute value and angle into a field upon creation? Well, obviously the memory footprint of the class is now a bit larger and also, counting the the results for every instance created may be also contra productive if these two methods are called seldom.

public final class EagerCachingComplex implements Complex {

    private final double real;
    private final double imaginary;

    private final double absolute;
    private final double angle;

    public EagerCachingComplex(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
        this.absolute = Math.sqrt((real * real) + (imaginary * imaginary));
        this.angle = absolute == 0 ? 0 : (Math.acos(real / absolute()) * Math.signum(imaginary));
    }

    // real() and imaginary() stay the same...

    @Override public double absolute() {
        return absolute;
    }

    @Override public double angle() {
        return angle;
    }
}

A third possibility I came up with is to compute the absolute value and angle lazily, on the first time they are required. But as you can see, this makes the code a bit cluttered and error prone. Also, I’m not sure if the use of volatile modifier is actually correct in this context.

public final class LazyCachingComplex implements Complex {

    private final double real;
    private final double imaginary;

    private volatile Double absolute;
    private volatile Double angle;

    public LazyCachingComplex(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    // real() and imaginary() stay the same...

    @Override public double absolute() {
        if (absolute == null) {
            absolute = Math.sqrt((real * real) + (imaginary * imaginary));
        }
        return absolute;
    }

    @Override public double angle() {
        if (angle == null) {
            angle = absolute() == 0 ? 0 : (Math.acos(real / absolute()) * Math.signum(imaginary));
        }
        return angle;
    }

}

So my question is, which of these three approaches is the best? Is there some other even better approach? Should I care about performance at all and stay with the first approach and think about optimizations only when performance becomes a real problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T05:37:20+00:00Added an answer on May 30, 2026 at 5:37 am

    I’d go for NonCachingComplex pretty much every time.

    Reasons:

    • It’s the simplest – so you should write it this way first and only make things more complex if you prove that it is necessary through benchmarking. Avoid premature optimization and all that!
    • The formulae for calculating absolute() and angle() are probably not expensive enough to justify caching. Floating point operations on modern CPUs are very fast, often even faster than fetching a value from memory.
    • Lowest memory footprint – this is beneficial not only for reducing the overall memory consumption of your code, but it also improves performance because more of your data will fit in the higher-speed processor caches. This can make a big difference for certain working set sizes.

    Of the others, LazyCachingComplex is particularly bad, since it is using boxed values for absolute and angle (which implies an extra memory dereference to access, plus two extra lots of object overhead). I think it unlikely that would ever see a performance benefit from doing this.

    Note that if you really care about performance then you wouldn’t use a Complex interface either – the best performance is from directly making a final Complex class, and referring to this class directly in your code. Method invocations via an interface are (slightly) more costly than method invocations on a final class.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have a simple XHTML document that uses a custom namespace for attributes:
Suppose I have the following (trivially simple) base class: public class Simple { public
Lets suppose that I have the following simple query var q = from p
I have a simple question. Is there a way ( using reflections I suppose
Suppose you have a COM interface ICOMInterface that is implemented by coclasses Coclass1 and
Suppose you have a generic interface and an implementation: public interface MyInterface<T> { void
Suppose I have an interface: public interface FooInterface { public void someMethod(); } and
Suppose I have an IBookRepository interface and implemented by SybaseAsaBookRepository and XMLBookRepository. SybaseAsaBookRepository constructor
Probably a simple question. I have an interface (MyInterface) that defines a property like
Suppose I have an interface for a service: public interface IFooService { void DoSomething();

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.