0

Will the following javascript

var StaticTest_A = (function () {
  function StaticTest_A() {
  }
  StaticTest_A.GetConstant = function () {
    return StaticTest_B.MyNumber + StaticTest_B.MyNumber;
  };
  return StaticTest_A;
})();
var StaticTest_B = (function () {
  function StaticTest_B() {
}
StaticTest_B.MyNumber = 5;
  return StaticTest_B;
})();

generated from this TypeScript

class StaticTest_A
{
   static GetConstant():number
   {
       return StaticTest_B.MyNumber + StaticTest_B.MyNumber;
   }
}

class StaticTest_B
{
   static MyNumber = 5;
}

be compiled so StaticTest_A.GetConstant() returns a constant or will the function be calculated on every call?

Oriol
  • 274,082
  • 63
  • 437
  • 513
noontz
  • 1,782
  • 20
  • 29

1 Answers1

3

No, that expression will run each time and it should because StaticTests_B.MyNumber could change in the meantime, as Pointy pointed out. Additionally, TypeScript doesn't change the code you write to improve the performance—that's actually a non-goal of the compiler.

If you only want the calculation to happen once for performance reasons then you will have to come up with your own solution to that. For example, you could create a reusable decorator that caches the value the first time it's run and then returns the cached value afterwards. You could then use that decorator anywhere you like:

function methodMemoize(target: Function | Object, key: string, descriptor: TypedPropertyDescriptor<() => any>) {
    const originalValue = descriptor.value;
    let hasRun = false;
    let returnedValue: any;

    descriptor.value = function(...args: any[]) {
        if (!hasRun) {
            returnedValue = originalValue.apply(this, args);
            hasRun = true;
        }

        return returnedValue;
    };
}

class StaticTest_A
{
    @methodMemoize
    static GetConstant()
    {
        console.log("run only once");
        return StaticTest_B.MyNumber + StaticTest_B.MyNumber;
    }
}

class StaticTest_B
{
   static MyNumber = 5;
}

StaticTest_A.GetConstant(); // "run only once", returns 10
StaticTest_A.GetConstant(); // returns cached 10
Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178