我很好奇 - 有時我會在我的代碼中進行更改,重新編譯,然後將我的exe或dll文件複製到舊版本中,然後看到Windows告訴我文件的日期已更改,但大小保持不變。這是爲什麼?爲什麼代碼中的小改動會影響exe文件的大小?
作爲一個例子,我用下面的控制檯應用程序進行測試:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
Console.WriteLine(a + b);
}
}
}
這產生的5120個字節(的Visual Studio 2012,調試生成)一個exe文件。然後,我將代碼更改爲:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = 3;
Console.WriteLine(a + b + c);
}
}
}
exe的大小完全相同。
我看拆卸,這是示出了在IL代碼的差,所以它不能是該差被優化掉:
第一版本:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 15 (0xf)
.maxstack 2
.locals init (int32 V_0,
int32 V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldloc.0
IL_0006: ldloc.1
IL_0007: add
IL_0008: call void [mscorlib]System.Console::WriteLine(int32)
IL_000d: nop
IL_000e: ret
} // end of method Program::Main
第二個版本:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 19 (0x13)
.maxstack 2
.locals init ([0] int32 a,
[1] int32 b,
[2] int32 c)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldc.i4.3
IL_0006: stloc.2
IL_0007: ldloc.0
IL_0008: ldloc.1
IL_0009: add
IL_000a: ldloc.2
IL_000b: add
IL_000c: call void [mscorlib]System.Console::WriteLine(int32)
IL_0011: nop
IL_0012: ret
} // end of method Program::Main
如果代碼體積較大,文件的大小應該如何?這只是一些隨機的機會?它發生在我身上(當對代碼進行小的更改時)...
總之:對齊。 – Fizz 2015-01-21 04:10:45
5120正好是10個扇區。看起來像一些填充。也許也可以對齊(如果實際代碼後面跟着應該扇區對齊的其他東西)。 – morfizm 2015-01-21 04:11:54