Skip to content
This repository has been archived by the owner on Sep 20, 2021. It is now read-only.

Commit

Permalink
Optimize lexing. #performance
Browse files Browse the repository at this point in the history
We replace a call to strpos() with a modified regular expression. In
fact, “0 === strpos(…)” is strictly equivalent to “^($regex)” in the
preg_match() call.
Moreover, we can remove a call to count().
  • Loading branch information
Hywan committed May 22, 2013
1 parent 255a4ef commit 39e8900
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions Llk/Lexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,20 +192,18 @@ protected function matchLexeme ( $lexeme, $regexp ) {

$_regexp = str_replace('#', '\#', $regexp);

if( 0 !== preg_match('#' . $_regexp . '#u', $this->_text, $matches)
&& 0 < count($matches)) {
if(0 !== preg_match('#^(' . $_regexp . ')#u', $this->_text, $matches)) {

if('' === $matches[0])
throw new \Hoa\Compiler\Exception\Lexer(
'A lexeme must not match an empty value, which is the ' .
'case of "%s" (%s).', 1, array($lexeme, $regexp));

if(0 === strpos($this->_text, $matches[0]))
return array(
'token' => $lexeme,
'value' => $matches[0],
'length' => strlen($matches[0])
);
return array(
'token' => $lexeme,
'value' => $matches[0],
'length' => strlen($matches[0])
);
}

return null;
Expand Down

0 comments on commit 39e8900

Please sign in to comment.