Posted to tcl by used____ at Sun Jun 12 10:12:14 GMT 2022view raw

  1. # test speed of dict vs array access vs switch
  2.  
  3. namespace eval ::ns {
  4. variable arr
  5. variable dic
  6.  
  7. proc init {{n 100}} {
  8. variable arr
  9. variable dic
  10.  
  11. catch {array unset arr}
  12. catch {unset dic}
  13.  
  14. set dic [dict create]
  15. array set arr {}
  16.  
  17. set ps "proc ::ns::tests {{n 100}} {\n for {set i 0} {\$i < \$n} {incr i} {\n switch -exact \$i {"
  18.  
  19. for {set i 0} {$i < $n} {incr i} {
  20. set v "v$i"
  21. set arr($i) $v
  22. dict append dic $i $v
  23. append ps "\n $i {set x $i}"
  24. }
  25.  
  26. append ps "\n }\n }\n}\n"
  27. eval $ps
  28. }
  29.  
  30. proc test0 {{n 100}} {
  31. for {set i 0} {$i < $n} {incr i} {
  32. }
  33. }
  34.  
  35. proc testa {{n 100}} {
  36. variable arr
  37.  
  38. for {set i 0} {$i < $n} {incr i} {
  39. set x $arr($i)
  40. }
  41. }
  42.  
  43. proc testd {{n 100}} {
  44. variable dic
  45.  
  46. for {set i 0} {$i < $n} {incr i} {
  47. set x [dict get $dic $i]
  48. }
  49. }
  50.  
  51. }
  52.  
  53. ### tests
  54. set N 1000
  55.  
  56. ::ns::init $N
  57.  
  58. puts "speed comparison array get/dict get/switch; by used___; version: 0"
  59. puts "init: $N entries"; ::ns::init $N
  60. puts "overhead: ::ns::test0 [time ::ns::test0 $N]"
  61. puts "array get: ::ns::testa [time ::ns::testa $N]"
  62. puts "dict get: ::ns::testd [time ::ns::testd $N]"
  63. puts "switch: ::ns::tests [time ::ns::tests $N]"
  64.