Global Variables vs onUpdate Calculations Efficiency

I currently have a watch face where I define about 30 global variables to map out all my x,y coordinates for all the data fields, lines, icons and such.  Those are then used in all the dc.draw commands in the onUpdate section.  I have put a couple snips below.

My thought was that doing all those calculations over and over on every onUpdate would be costly to perform if I did the calculations in the dc.draw commands.  So I put all the calculations as global variables thinking I could save battery by doing them once and then referencing the variables.

My question is which is more efficient/uses less battery?  Carrying all those global variables or having no global variables and doing the calculations on every onUpdate?    

Example

above all the functions....

var dH = System.getDeviceSettings().screenHeight;
var dM = dH/2;
var tR1 = dH*.11;
var tR1L = dH*.36;
var tR5 = dM+17;
var lH3 = dH*.675;
var tR6 = dH*.7425;
var tR6L = dH*.26;
var ftR6R = dH*.32;
var lH4 = dH*.8325;

....

onUpdate

dc.drawLine(0,lH1,dH,lH1);

dc.drawText(tR1L, tR1, font,.......;

  • Avoid globals.  They can have side effects in this case if you ever add a background service, the scope can be an issue..

    What you may want to do is declare them in your view class, like this:

    class SLeanView extends Ui.WatchFace {
    	var width,height,centerW,centerH;
    	var radius;
    	var largeF,largeH,mediumF,mediumH,secW;
    	var smallF,smallH;
    	var iconF,iconW;
    	var timeY,secY,iconY,batY,hrY,stepY;
    	var secX,dateX;

    What I then do is set their values in onLayout().  You have the dc at that time, so you can use things like dc.getHeight(), dc.getFontHeight, dc.getTextWidthInPixels, to determine the x/y for things, spacing between lines, width of a string for seconds, etc.

  • I should have said exactly where above the functions...the variables are actually in the class like below.

    With that said would you still recommend moving them down into the onUpdate section or leave them like they are? Am I saving any battery by having them outside the onUpdate?

    class GarminWatchFaceView extends WatchUi.WatchFace {
    var dH = System.getDeviceSettings().screenHeight;
    var dM = dH/2;
    var tR1 = dH*.11;
    var tR1L = dH*.36;

    ....

    function initialize() {
    WatchFace.initialize();
    }

    function onLayout(dc) {
    }

    function onShow() {
    }

    function onUpdate(dc) {
    dc.setColor(Graphics.COLOR_TRANSPARENT, backColor);
    dc.clear();
    dc.setColor(gridColor, Graphics.COLOR_TRANSPARENT);
    dc.setPenWidth(gridThickness);
    dc.drawLine(0,lH1,dH,lH1);

    .....

  • Keep them where they are.  You don't want things recalculates each time onUpdate is called.