Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Why is populating a square matrix faster than populating a long vector with the same number of elements?

    Good afternoon,

    It is a lot faster to populate a 100 X 100 matrix, than to populate a 10000 X 1 vectors. Why is that?

    The code:
    Code:
    clear all
    
    timer on 1
    
    matrix A = J(10000,1,.)
    
    forvalues i=1/10000 {
        matrix A[`i',1] = 1
    }
    
    timer off 1
    
    timer on 2
    
    matrix B = J(100,100,.)
    forvalues i = 1/100 {
        forvalues j = 1/100 {
            matrix B[`i',`j'] = 1
        }
    }
    
    timer off 2
    
    timer list
    results in

    Code:
    . timer list
       1:      0.33 /        1 =       0.3340
       2:      0.03 /        1 =       0.0310
    So populating the square matrix is 10 times faster.

  • #2
    Code:
    timer on 11
    matrix A = J(10000,1,.)
    timer off 11
    
    timer on 12
    forvalues i=1/10000 {
        matrix A[`i',1] = 1
    }
    timer off 12
    
    timer on 21
    matrix B = J(100,100,.)
    timer off 21
    
    timer on 22
    forvalues i = 1/100 {
        forvalues j = 1/100 {
            matrix B[`i',`j'] = 1
        }
    }
    timer off 22
    
    timer list
    results in
    Code:
    . timer list
      11:      0.46 /        1 =       0.4580
      12:      0.19 /        1 =       0.1860
      21:      0.00 /        1 =       0.0000
      22:      0.17 /        1 =       0.1750
    So creating the square matrix is infinitely faster, apparently.

    Comment


    • #3
      I get similar results with your code using v. 15.1. I would hazard a guess that this is related to some issues of how matrices are allocated that came up in discussions several years ago about how a larger -set matsize- value can badly impair performance, at least in earlier Stata versions. See:

      https://www.statalist.org/forums/for...mp2-vs-v-12-ic

      https://www.statalist.org/forums/for...ng-set-matsize

      Comment

      Working...
      X