When users have many extensions that need to be loaded, developers of SketchUp extensions can help the startup cycle by using conditional require
statements.
Since (at least) the SketchUp 2016 release, the "Tools"
folder files have been loaded first before any of the files in the "Plugins"
folder. This means that "extensions.rb"
, "langhandler.rb"
and "sketchup.rb"
are likely already loaded (in this order) by the time any extension begins loading.
If your extension files use plain require
statements to ensure that these files are loaded, then SketchUpâs Ruby has to do slow string comparison of the script name argument against every path member in the $LOADED_FEATURES
array, each and everytime a non-conditional require
statement is executed.
Your code files can instaed use conditional modifiers to only execute the require
statements when necessary.
Example of a set of plain require
statements used by many extension authors:
require 'sketchup.rb' # internally calls "require 'langhandler.rb'"
require 'extensions.rb'
require 'langhandler.rb' # frivolous
Example of conditional require
statements:
require 'sketchup.rb' unless Object.private_method_defined?(:file_loaded)
require 'extensions.rb' unless defined?(SketchupExtension)
require 'langhandler.rb' unless defined?(LanguageHandler)
If you prefer if not
rather than unless
that will also work fine.
The point is that testing for class and method object existence is way faster than comparing a substring against a growing list of absolute path strings (in the $LOADED_FEATURES
array.)
The same sort of thing can be used with an extension that has multiple files to load at startup, if the files are not encrypted or scrambled.
If an extension has an internal indicator of whether it is loading for the first time (ie. an @@loaded
variable?,) then Kernel#load
could be used instead.
if not @@loaded
load 'main.rb'
load 'commands.rb'
load 'menus.rb'
end
Now if we could also get Sketchup::require
changed so that it will skip the $LOADED_FEATURES
comparison during the startup cycle, and just load files (similar to a Kernel#load
call,) then startups could get considerably faster.
If ALL extensions used conditional require
statements then the startup cycle would be faster for those users who load many plugins.