Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hardcoding values vs. reading from file

This is a general question about the efficiency of hardcoding data - I'm writing a program in Java that does some chemical analysis, and I need to use the isotopic abundances of different elements. The way I have it set up right now is that all values (which never need to be modified) are stored as final fields in my class, i.e.

static final double C12Abundance = .989;
static final double C12Mass = 12;

A lot of similar programs store this type of data in an XML file, then read the values from there, like this:

<compounds>
<elements>
    <element symbol='C' mono_isotopic_mass ='12.00000000000' abundance='.989'/>

Is there any reason (performance, memory, etc) to read from it this way? Seems easier to just leave it as a field.

like image 514
Sevy Avatar asked Nov 19 '25 18:11

Sevy


2 Answers

Hard coding is way much faster in terms of performance and memory allocation.

The thing you gain from reading from a file is code re-usability (running your program with different parameters without the need to recompile it).

Note that reading from a file has the following steps:

  1. Declare variable to use for storing a value.
  2. Create an input (stream) object
  3. Initialize it with a path
  4. Open The file from FS
  5. Find the correct line to read from
  6. Read the value
  7. Store it in the variable above
  8. Close the input (stream)

That's a pretty big overhead instead of having a pre-compiled final variable with a value

like image 160
MaVRoSCy Avatar answered Nov 21 '25 08:11

MaVRoSCy


As these are truely universal constants, properties limited in number, you can put them in code, but nicely organized.

public enum Element {
    //  Name Mass  Abund
    C12("C", 12.0, .989),
    He4(...),
    O32(...),
    ...;

    public final String name;
    public final double monoIsotopicMass;
    public final double abundancy;

    private Element(String name, double monoIsotopicMass, double abundancy) {
        this.name = name;
        this.monoIsotopicMass = monoIsotopicMass;
        this.abundancy = abundancy;
    }
}

for (Element elem : Element.values()) {
    if (elem.abundancy > 0.5) {
        ...
    }
}
like image 43
Joop Eggen Avatar answered Nov 21 '25 08:11

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!