Skip to content
Tcl Source Code View Ticket
Login

View Ticket

Improve performance of tcl_startOfNextWord and friends...

Closed / Fixed1764318fffffffffffffffffffffffffffffffffCreated 19 years agoUpdated 19 years ago
Descriptionplain2007-07-31 11:09:09
Hi all,

I have recently noticed that the file word.tcl in the tcl library has not been updated to use the (relatively) new -start option of regexp. Changing the file word.tcl to remove [string range ...] call and use the -start regexp option, all the procs were made much faster, especially for large strings. 
As an example, the body of tcl_startOfNextWord:

proc tcl_startOfNextWord {str start} {
    global tcl_nonwordchars tcl_wordchars
    if {[regexp -indices "$tcl_wordchars*$tcl_nonwordchars+$tcl_wordchars" \
        [string range $str $start end] result]} {
    return [expr {[lindex $result 1] + $start}]
    }
    return -1
}

Can be changed to:

proc tcl_startOfNextWord {str start} {
    global tcl_nonwordchars tcl_wordchars
    if {[regexp -indices -start $start -- \
"$tcl_wordchars*$tcl_nonwordchars+$tcl_wordchars" \
        $str result]} {
    return [lindex $result 1]
    }
    return -1
}
petasis Ticket [1764318fff]: 2 changes [History diff]2007-07-31 18:10:19
dgp Ticket [1764318fff]: 3 changes [History diff]2007-08-01 11:39:42
dkfplain2007-08-01 22:21:36
Logged In: YES 
user_id=79902
Originator: NO

Reworked so that code is much more efficient (avoids repeated recompilation of regular expressions, uses -start, etc.) To illustrate, here's the committed version of tcl_startOfNextWord:
  proc tcl_startOfNextWord {str start} {
      variable ::tcl::WordBreakRE
      set result {-1 -1}
      regexp -indices -start $start $WordBreakRE(next) $str result
      return [lindex $result 1]
  }
That's about as efficient as we're going to get. :-)

Note that not all operations can take full advantage of the efficiency gains. Can't be helped.
Log in (anonymous is fine) to add a comment.