Cache result of Language::isValidCode() to avoid regex processing
authorlwelling <lwelling@wikimedia.org>
Fri, 3 May 2013 00:34:25 +0000 (20:34 -0400)
committerlwelling <lwelling@wikimedia.org>
Fri, 3 May 2013 00:41:18 +0000 (20:41 -0400)
The function can be called over 2000 times in generating a page. This way
is significantly faster even for random invalid codes.  For real use it
should avoid the regex most of the time with no change in behavior.

Change-Id: I9fcbae1770be0d3f405d3d12254c11943b0d5f46

languages/Language.php

index b9201d7..84e7f37 100644 (file)
@@ -326,13 +326,19 @@ class Language {
         * @return bool
         */
        public static function isValidCode( $code ) {
-               return
-                       // People think language codes are html safe, so enforce it.
-                       // Ideally we should only allow a-zA-Z0-9-
-                       // but, .+ and other chars are often used for {{int:}} hacks
-                       // see bugs 37564, 37587, 36938
+               static $cache = array();
+               if( isset( $cache[$code] ) ) {
+                       return $cache[$code];
+               }
+               // People think language codes are html safe, so enforce it.
+               // Ideally we should only allow a-zA-Z0-9-
+               // but, .+ and other chars are often used for {{int:}} hacks
+               // see bugs 37564, 37587, 36938
+               $return =
                        strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
                        && !preg_match( Title::getTitleInvalidRegex(), $code );
+               $cache[ $code ] = $return;
+               return $return;
        }
 
        /**