2

我有两个函数,它们的内容非常相似。

// mock-up code

bool A() {
    while(1000000) {
        // 3 lines of A() specific code
        // 15 lines of shared code, pasted in
        // 1 lines of A() specific code
    }
}
bool B() {
    while(1000000) {
        // 2 lines of B() specific code
        // 15 lines of shared code, pasted in
        // 2 lines of B() specific code
    }
}     

我不想将 15 行共享代码粘贴到两个函数中(因为这些行非常复杂,如果我稍后更改该代码,我不想记住在两个地方都更改它) .

如果我将这 15 行代码放入一个单独的函数中,则会对性能造成重大影响(JIT 拒绝内联它;可能是由于参数列表中的结构和/或“复杂”的流控制元素)。

还有其他方法吗,还是我运气不好?

4

2 回答 2

0

This 'significant' performance hit you're talking about is much less significant than what you think.

If it is so significant, You can try to tell to the JIT compiler to inline it using MethodImplOptions Enumeration, Though he should do it if the method is not virtual. For more information.

Example (From MSDN) :

using System;
using System.Globalization;
using System.Runtime.CompilerServices;

public class Utility
{
   [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] 
   public static string GetCalendarName(Calendar cal)
   {
      return cal.ToString().Replace("System.Globalization.", "").
                 Replace("Calendar", "");
   }
}
于 2013-03-31T08:41:02.170 回答
-1

Let's not look for something too involved, what about that? Not so clean, but that may be the price you have to pay to have both non-reproduction and performance:

boolean AorB (boolean flagA) {
    while(1000000) {
        if (flagA) {
            // 3 lines of A() specific code
        }
        else {
            // 1 line of B() specific code
        }

        // 15 lines of shared code, pasted in

        if (flagA) {
            // 2 lines of A() specific code
        }
        else {
            // 2 lines of B() specific code
        }
    }
}
于 2013-03-31T08:51:39.627 回答