Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Efficient Way to Scale an Array in Java?

(Apologies if this has been asked before - I can't believe it hasn't, but I couldn't find one. Perhaps my search-fu is weak.)

For years I've "known" that Java has no native function to scale an array (i.e. multiply each element by a constant). So I've been doing this:

for (int i=0; i<array.length; i++) {
  array[i] = array[i] * scaleFactor;
}

Is this actually the most efficient way (in this application, for example, it's an array of around 10000 doubles)? Or is there a better way?

like image 866
Ian Renton Avatar asked Oct 17 '11 09:10

Ian Renton


2 Answers

Looks absolutely fine to me. I can't think of a more efficient way. Obviously try to put that code in one place rather than having the actual code all over the place, but other than that, no obvious problems.

like image 161
Jon Skeet Avatar answered Sep 24 '22 07:09

Jon Skeet


Only other suggestion I can offer is to lazily scale whereby you only pay the cost of multiplication on accessing each element; e.g.

public class MyArray {
  private final double[] arr;
  private double scale = 1.0;

  public MyArray(double[] arr) {
    this.arr = arr;
  }

  public double getScale() {
    return scale;
  }

  public void setScale(double scale) {
    this.scale = scale;
  }

  public double elementAt(int i) {
    return arr[i] * scale;
  }
}

Obviously this is only better in certain situations:

  • When your array is huge AND
  • You are only accessing a few elements AND
  • You are typically accessing these elements once.

In other situations it's a micro-optimisation with no real benefit on modern CPUs.

like image 30
Adamski Avatar answered Sep 23 '22 07:09

Adamski