diff --git a/Tracking/TrkFitter/TrkGlobalChi2Fitter/CMakeLists.txt b/Tracking/TrkFitter/TrkGlobalChi2Fitter/CMakeLists.txt
index 3b018d477cc9aee3a053ee51fdd73e14c2ebcb1a..0577de5ee4097a6dd34c784542de2d5e638e5026 100644
--- a/Tracking/TrkFitter/TrkGlobalChi2Fitter/CMakeLists.txt
+++ b/Tracking/TrkFitter/TrkGlobalChi2Fitter/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir(TrkGlobalChi2Fitter)
@@ -14,3 +14,17 @@ atlas_add_component (
     src/components/*.cxx
     INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} ${EIGEN_INCLUDE_DIRS}
     LINK_LIBRARIES ${CLHEP_LIBRARIES} ${EIGEN_LIBRARIES} AthenaBaseComps AtlasDetDescr EventPrimitives GaudiKernel IdDictDetDescr InDetReadoutGeometry MagFieldConditions MagFieldElements TrkCompetingRIOsOnTrack TrkDetDescrInterfaces TrkEventPrimitives TrkExInterfaces TrkExUtils TrkFitterInterfaces TrkFitterUtils TrkGeometry TrkMaterialOnTrack TrkMeasurementBase TrkParameters TrkPrepRawData TrkPseudoMeasurementOnTrack TrkRIO_OnTrack TrkSegment TrkSurfaces TrkToolInterfaces TrkTrack TrkTrackSummary TrkVertexOnTrack TrkVolumes )
+
+
+# Code in this file makes heavy use of eigen and runs orders of magnitude
+# more slowly without optimization.  So force this to be optimized even
+# in debug builds.  If you need to debug it you might want to change this.
+# Specifying optimization via an attribute on the particular
+# function didn't work, because that still didn't allow inlining.
+if ( "${CMAKE_BUILD_TYPE}" STREQUAL "Debug" )
+  set_source_files_properties(
+     ${CMAKE_CURRENT_SOURCE_DIR}/src/GlobalChi2Fitter.cxx
+     PROPERTIES
+     COMPILE_FLAGS "${CMAKE_CXX_FLAGS_RELWITHDEBINFO}"
+     COMPILE_DEFINITIONS "FLATTEN" )
+endif()
diff --git a/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx b/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx
index f0aaea724bc26ebfba4e18dd73cf52e32433e7fd..8f89520720e93b3ee1642f86d894e2d2b3037f6c 100644
--- a/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx
+++ b/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx
@@ -7903,6 +7903,14 @@ namespace Trk {
     );
   }
 
+#if defined(FLATTEN) && defined(__GNUC__)
+// We compile this package with optimization, even in debug builds; otherwise,
+// the heavy use of Eigen makes it too slow.  However, from here we may call
+// to out-of-line Eigen code that is linked from other DSOs; in that case,
+// it would not be optimized.  Avoid this by forcing all Eigen code
+// to be inlined here if possible.
+__attribute__ ((flatten))
+#endif
   void GlobalChi2Fitter::calculateJac(
     Eigen::Matrix<double, 5, 5> & jac,
     Eigen::Matrix<double, 5, 5> & out,