Method calls Vs local variables

Hi

I'm making a change in the code wherein the same method gets called twice.

getString(

resultSet.getString(DAOConstants.BENEFITFLAG)

Now would assignin it to a local variable be of advantage (its called only twice) for performance - the code gets called average at 340 hits/min.

wat are the pros and cons of either method

[361 byte] By [AbiSSa] at [2007-11-26 16:02:51]
# 1
Is that the line of code that gets called twice?You will save some time by only calling it once.Kaj
kajbja at 2007-7-8 22:24:41 > top of Java-index,Java Essentials,Java Programming...
# 2

Why rely on what other people tell you when you can easily profile it yourself? You can use the simple trick of measuring the System.currentTimeInMillis() before and after the calls and then substracting the first from the second to get how much milliseconds the calls took. Then create some test that does this 300 times in sequence and see which method takes longer.

gimbal2a at 2007-7-8 22:24:41 > top of Java-index,Java Essentials,Java Programming...
# 3

Your code example doesn't make much sense. Actually in that kind of example, generally you couldn't store the return value because it would mean different things. But who can tell?

It's often good to assign the result of a method call to a local variable if it's going to be used more than once. Partially it's for efficiency, but it's more of a correctness issue: calling the code may have side effects, and you may not want those side effects to happen more than once. On the other hand, generally it's a bad thing for an accessor method to have side effects.

340 calls per minute isn't a whole hell of a lot. It's not trivial but it's not overwhelming either.

paulcwa at 2007-7-8 22:24:41 > top of Java-index,Java Essentials,Java Programming...
# 4

I understand its a trivial question, but I wanted to know from the experienced guys like how they resolve such things.

- the resultset returns the same value for the same instance(no sweat ter)

-If i could calculate then i'd have done it - the time varies greatly depending on the server load which would nullify such tests.

AbiSSa at 2007-7-8 22:24:41 > top of Java-index,Java Essentials,Java Programming...
# 5

Well, there's nothing to resolve unless there's a problem.

Generally, I'd say to cache it in a local variable, not for efficiency (well, not for time efficiency) but for clarity. (Clarity leads to programmer efficiency.) If you put it in a variable with a meaningful name, it can be more obvious what it's doing, and that means the code can be read and understood by a maintainer more quickly, and that means that future projects will be less painful.

paulcwa at 2007-7-8 22:24:41 > top of Java-index,Java Essentials,Java Programming...