Posted to tcl by used____ at Sun Jun 12 10:12:14 GMT 2022view raw
- # test speed of dict vs array access vs switch
- namespace eval ::ns {
- variable arr
- variable dic
- proc init {{n 100}} {
- variable arr
- variable dic
- catch {array unset arr}
- catch {unset dic}
- set dic [dict create]
- array set arr {}
- set ps "proc ::ns::tests {{n 100}} {\n for {set i 0} {\$i < \$n} {incr i} {\n switch -exact \$i {"
- for {set i 0} {$i < $n} {incr i} {
- set v "v$i"
- set arr($i) $v
- dict append dic $i $v
- append ps "\n $i {set x $i}"
- }
- append ps "\n }\n }\n}\n"
- eval $ps
- }
- proc test0 {{n 100}} {
- for {set i 0} {$i < $n} {incr i} {
- }
- }
- proc testa {{n 100}} {
- variable arr
- for {set i 0} {$i < $n} {incr i} {
- set x $arr($i)
- }
- }
- proc testd {{n 100}} {
- variable dic
- for {set i 0} {$i < $n} {incr i} {
- set x [dict get $dic $i]
- }
- }
- }
- ### tests
- set N 1000
- ::ns::init $N
- puts "speed comparison array get/dict get/switch; by used___; version: 0"
- puts "init: $N entries"; ::ns::init $N
- puts "overhead: ::ns::test0 [time ::ns::test0 $N]"
- puts "array get: ::ns::testa [time ::ns::testa $N]"
- puts "dict get: ::ns::testd [time ::ns::testd $N]"
- puts "switch: ::ns::tests [time ::ns::tests $N]"