0

I have a pretty time consuming Excel macro, with a lot of input data. First, i load these data into an array (arr).

Is this code

for n =1 to 1000000
...
arr(n,1)=arr(n,2)+arr(n,4)*arr(n,78) 
...
next n

faster than this

for n =1 to 1000000
...
Sensor_Top=arr(n,2)
Age       =arr(n,4)
Material  =arr(n,78)
output    =Sensor_Top+Age*Material
arr(n,1)  =output
...
next n

?

So in other words, i would like to include unnecessary variable declarations for readability. Does VBA do some sort of JIT compiling to deal with this?

4
  • Assuming arr came from a worksheet, why wouldn't arr(n, 1) be precomputed on the Excel worksheet in the first place? Why write any code to do a calculation whose result you can readily grab along with the rest of the data? Commented Nov 21, 2019 at 17:34
  • It does not. This was probably unclear in this toy example. In reality the calculations are a lot more involved. (I load the input data into an array, and then populate a different output array with the results. As last step i copy the output array back into the worksheet.) Commented Nov 21, 2019 at 17:50
  • Consider putting your actual code up for peer review on Code Review if you're interested in feedback on any/all aspects of the code, including (but not limited to) performance. Commented Nov 21, 2019 at 18:10
  • "Is this code […] faster than this […]?" - did you run it and try it? Commented Nov 21, 2019 at 19:58

3 Answers 3

4

These helper variables will have negligible effect on the the performance. Using an enumeration would be more efficient.

Public Enum NamedArrayColumns
    output = 1
    Sensor_Top = 2
    Age = 4
    Material = 78
End Enum

Sub Foo()
    Rem Some Code

    For n = 1 To 1000000
        arr(n, output) = arr(n, Sensor_Top) + arr(n, Age) * arr(n, Material)
    Next n

End Sub
Sign up to request clarification or add additional context in comments.

Comments

4

Not that I know of, but then again it's not like VBA to P-Code compilation is so completely documented that this kind of thing is easy to see.

I doubt the compiler does any inlining or other kind of optimization, but I could be wrong (VB6 did have optimization settings that did... something).

That said, write code for readability and maintainability.

If your code is too slow, the bottleneck isn't going to be what variables you're using.

As for whether A is faster than B... you have two horses - race them!

Comments

3

If you want to improve readability then this can also work:

const c_sensor_top as long = 2
const c_age as long = 4
const c_output as long = 78

for n = 1 to 1000000
    ...
    arr(n,1) = arr(n, c_sensor_top) + arr(n, c_age) * arr(n, c_output) 
    ...
next n

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.