Posted to tcl by dbohdan at Mon Jun 12 10:19:51 GMT 2017view raw

  1. namespace eval ::poly {
  2. namespace export *
  3. proc index {value args} {
  4. ::poly::[lindex $value 0]::index $value {*}$args
  5. }
  6. proc length value {
  7. ::poly::[lindex $value 0]::length $value
  8. }
  9. }
  10. namespace eval ::poly::LIST {
  11. proc index {value args} {
  12. return [lindex [lindex $value 1] {*}$args]
  13. }
  14. proc length value {
  15. return [llength [lindex $value 1]]
  16. }
  17. }
  18. namespace eval ::poly::DICT {
  19. proc index {value args} {
  20. return [dict get [lindex $value 1] {*}$args]
  21. }
  22. proc length {value args} {
  23. return [dict size [lindex $value 1]]
  24. }
  25. }
  26.  
  27. namespace eval ::benchmark {
  28. namespace import ::poly::*
  29. }
  30.  
  31. set testValues {}
  32. for {set i 0} {$i < 10000} {incr i} {
  33. set tag [expr {$i % 2 == 0 ? "LIST" : "DICT"}]
  34. lappend testValues [list $tag [list foo$i bar$i baz$i qux$i hi yo]]
  35. }
  36.  
  37. proc ::benchmark::bench1 values {
  38. set result {}
  39. foreach value $values {
  40. set tag [lindex $value 0]
  41. set content [lindex $value 1]
  42. if {$tag == {LIST}} {
  43. lappend result [llength $content]
  44. } else {
  45. lappend result [dict size $content]
  46. }
  47. }
  48. return $result
  49. }
  50.  
  51. proc ::benchmark::bench2 values {
  52. set result {}
  53. foreach value $values {
  54. lappend result [length $value]
  55. }
  56. return $result
  57. }
  58.  
  59. puts [time {::benchmark::bench1 $testValues} 100]
  60. puts [time {::benchmark::bench2 $testValues} 100]
  61.