News for hackers. Stuff that matters.
Re:John Carmack on Inlined Code by orf on Wednesday October 09, 2024 @06:47AM (#41786380)
That’s gonna be quite expensive, don’t do this in hot loops. You’re re-defining and re-creating the function object each time the outer function is called.
Re:John Carmack on Inlined Code by gorgoiler on Wednesday October 09, 2024 @03:03PM (#41791464)
Good point. I measured it for 10^6 loops:

(1) 40ms for inline code;

(2) 150ms for an inner function with one expression;

(3) 200ms for a slightly more complex inner function; and

(4) 4000ms+ for an inner function and an inner class.

  def f1(n: int) -> int:
      return n * 2

  def f2(n: int) -> int:
      def g():
          return n * 2
  
      return g()
  
  def f3(n: int) -> int:
      def g():
          for _ in range(0):
              try:
                  pass
              except Exception as exc:
                  if isinstance(exc, 1):
                      pass
                  else:
                      while True:
                          pass
                  raise Exception()
          return n * 2
  
      return g()
  
  def f4(n: int) -> int:
      class X:
          def __init__(self, a, b, c):
              pass
  
          def _(self) -> float:
              return 1.23
  
      def g():
          for _ in range(0):
              try:
                  pass
              except Exception as exc:
                  if isinstance(exc, 1):
                      pass
                  else:
                      while True:
                          pass
                  raise Exception()
          return n * 2
  
      return g()