program size. lazarus / 62-General ---------------------------------------------------------------------- Seenkao · 2022-04-11 21:11 Я проводил тесты и выяснил, что статичные массивы в памяти программы занимают очень много места! Непропорционально много!!! Прикладываю код. В нём только та часть которую я менял. Google translate: I ran tests and found out that static arrays take up a lot of space in the program memory! A disproportionate amount!!! I am attaching the code. It contains only the part that I changed. Linux x86_64, Debian 10, FPC 3.2.0. Application is not LCL. Debug - off. -O3 -CX -XX Start code:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  n, m: integer;   procedure MyProc(zzz: longword);  begin  ...  inc(n);  inc(m);  end; begin  ...  n := 1;  m := 4;  MyProc(5);  MyProc(67);  MyProc(55);  MyProc(66);  MyProc(45);  ...  MyProc(33);  ...end;  Code when I tried to optimize:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  n, m: integer;  iArr: array[1..40] of byte = (5, 67, 55, 66, 45, 64, ..., 33);   procedure MyProc(zzz: longword);  begin  ...  inc(m);  end; begin  ...  m := 4;  for n := 1 to 40 do    MyProc(iArr[n]);  ...end;И в результате я получил "оптимизированный" код, больше чем изначальный! Я бы очень хотел знать, как массив из 40 байт может быть больше кода на 520 байт? Не считая цикла. Google translate: And as a result, I got "optimized" code, more than the original one! I would really like to know how an array of 40 bytes can be more than 520 bytes of code? Apart from the cycle. ---------------------------------------------------------------------- Seenkao · 2022-04-12 13:22 На Windows 32x оптимизация работает. Проблема проявляется только в Linux? С чем это связано? Google translate: Optimization works on Windows 32x. Does the problem only appear on Linux? What is it connected with? ---------------------------------------------------------------------- Red_prig · 2022-04-12 13:39 without assembler listing, nothing at all is clear ---------------------------------------------------------------------- marcov · 2022-04-12 13:48 An array definition is a constant, not code. To get sane answers, please post something reproducible, i.e. compilable code together with compiler target and used switches ---------------------------------------------------------------------- Seenkao · 2022-04-12 13:53 Quote from: Red_prig on April 12, 2022, 03:39:32 pmwithout assembler listing, nothing at all is clear какой ассемблерный код я должен предоставить? Где я могу посмотреть как формируется массив в системе на ассемблере? Где написано как инициализируется данный массив? Есть код, который я предоставил. Основываясь на нём видно, что минимальные (нативные) приложения увеличиваются на Linux если мы подобным образом пытаемся оптимизировать программу. Проблема не в том, что программа увеличивается в Linux, проблема в том, что если подобное увеличение программы происходит в Linux, значит и на других системах мы можем получить такой же результат! Исключая Windows. google translate: what assembler code should i provide? Where can I see how an array is formed in the system in assembler? Where is it written how this array is initialized? There is a code that I have provided. Based on it, it can be seen that minimal (native) applications increase on Linux if we try to optimize the program in this way. The problem is not that the program scales up on Linux, the problem is that if a similar program scales up on Linux, then we can get the same result on other systems! Excluding Windows. marcov, так-то код предоставлен, его вставить достаточно. Хорошо, я предоставлю программу где это происходит. Подождите немного. google translate: marcov, so the code is provided, just paste it. Okay, I'll provide a program where this happens. Wait a bit. ---------------------------------------------------------------------- marcov · 2022-04-12 15:09 So it is not about calls, but about series of calls taking up room. 64-bit assembly is more bulky than 32-bit, so that is no surprise. ---------------------------------------------------------------------- Seenkao · 2022-04-12 15:50 Quote from: marcov on April 12, 2022, 05:09:58 pmSo it is not about calls, but about series of calls taking up room. 64-bit assembly is more bulky than 32-bit, so that is no surprise. Это просто отписка, чтоб показать, что ни чего делаться не будет? Я могу собрать ту же программу под Windows 64 и можно утверждать на 99% что на Windows оптимизация будет работать. Как и во многих других случаях, которые я скидывал ранее в соседних топиках. Если не собираетесь ни чего делать, то так и пишите, а не надо сваливать с больной головы на здоровую! google translate: Is this just an unsubscribe to show that nothing will be done? I can compile the same program under Windows 64 and can be 99% sure that optimization will work on Windows. As in many other cases that I threw off earlier in neighboring topics. If you are not going to do anything, then write like that, and do not blame it "from a sick head to a healthy one"! Я извиняюсь за эмоции, но чем больше я тут общаюсь, тем больше вижу ваше не желание что-то делать. Особенно когда указывают на конкретные ошибки. Возможно это из-за того что я русский? (заблокируйте меня, и не парте мне мозги, я буду знать, что мне здесь не рады). Или из-за того что нахожу постоянно недочёты в работе компиляторов? (разве это плохо? Мы должны знать как можно сделать так, чтобы улучшить свой код). Я очень надеюсь, что я ошибаюсь!!! google translate: I apologize for the emotions, but the more I communicate here, the more I see your unwillingness to do something. Especially when specific errors are pointed out. Maybe it's because I'm Russian? (block me and don't brainwash me, I'll know I'm not welcome here). Or because of the fact that I constantly find shortcomings in the work of compilers? (Is it bad? We need to know how to do it in order to improve our code). I really hope I'm wrong!!!  Я скомпилировал свой проект для Windows 64 и как и ожидал - получил оптимизацию кода!!! Данный код не оптимизируется на Linux и занимает больше места, но оптимизируется на Windows! google translate: I compiled my project for Windows 64 and as expected - I got code optimization!!! This code is not optimized on Linux and takes up more space, but is optimized on Windows! ---------------------------------------------------------------------- MarkMLl · 2022-04-12 16:22 Quote from: Seenkao on April 12, 2022, 05:50:03 pmMaybe it's because I'm Russian? (block me and don't brainwash me, I'll know I'm not welcome here). Please don't try that here. Apart from that I agree that your initial question is a fair one but on what are you basing your "520 bytes of code" assertion? As others have said: too little information. MarkMLl ---------------------------------------------------------------------- Seenkao · 2022-04-12 16:29 Прилагаю готовое приложение. В данном приложении прекрасно видно то, о чём я писал ранее. Включите/отключите TEST_OPTIMIZED - чтобы код был "оптимизирован"/"не оптимизирован". google translate: I am attaching the completed application. In this application, you can clearly see what I wrote about earlier. Enable/disable TEST_OPTIMIZED - so that the code is "optimized"/"not optimized". ---------------------------------------------------------------------- 440bx · 2022-04-12 16:31 Quote from: Seenkao on April 11, 2022, 11:11:44 pmI would really like to know how an array of 40 bytes can be more than 520 bytes of code? Apart from the cycle. Your first piece of code initializes every array element individually.  IOW, you have "n" calls to the procedure, the compiler will generate code for "n" calls.  In the second case, which you call "optimized", instead of individual calls, you have a loop with a single call to the procedure. There is no mystery why one is code-wise bigger. If your array was a million elements and you initialized every element with an individual call to the procedure for every element (as in the first case), it would consume several megabytes of code. HTH. ---------------------------------------------------------------------- Seenkao · 2022-04-12 17:14 Quote from: 440bx on April 12, 2022, 06:31:56 pmYour first piece of code initializes every array element individually.  IOW, you have "n" calls to the procedure, the compiler will generate code for "n" calls.  In the second case, which you call "optimized", instead of individual calls, you have a loop with a single call to the procedure. тайна... ))) Если почитаешь что я пишу, то может поймёшь, что код с циклом занимает больше памяти, чем код без оптимизации. google translate: secret...))) If you read what I write, you may understand that the code with the cycle takes more memory than the code without optimization. MarkMLl, хотя бы подскажи что делать. Я не очень хочу делать для таких случаев динамические массивы и "вручную" заполнять их. Потому что я буду понимать, что так я минимизирую расходы. А может и нет, я не проверял. google translate: MarkMLl, at least tell me what to do. I do not really want to make dynamic arrays for such cases and "manually" fill them. Because I will understand that in this way I will minimize costs. Or maybe not, I haven't checked. ---------------------------------------------------------------------- 440bx · 2022-04-12 17:17 Quote from: Seenkao on April 12, 2022, 07:14:58 pmsecret...))) If you read what I write, you may understand that the code with the cycle takes more memory than the code without optimization. I read what you wrote.  An observation is in order now, what you write isn't always "easy" to understand. ---------------------------------------------------------------------- MarkMLl · 2022-04-12 17:27 Quote from: Seenkao on April 12, 2022, 07:14:58 pmMarkMLl, хотя бы подскажи что делать. Я не очень хочу делать для таких случаев динамические массивы и "вручную" заполнять их. Потому что я буду понимать, что так я минимизирую расходы. А может и нет, я не проверял. google translate: MarkMLl, at least tell me what to do. I do not really want to make dynamic arrays for such cases and "manually" fill them. Because I will understand that in this way I will minimize costs. Or maybe not, I haven't checked. As several other people have said: we need more information. Two things do stand out though: a) You say that you have a 40-byte array but 260 bytes of code. You need to look at the assembler output, since what's probably happening there is that the initial 40 bytes are being stored in a read-only code section and being copied to a read-write one at runtime: this requires code. b) The optimised version of your program is larger. Again, look at the assembler: optimisation is probably unrolling a loop. MarkMLl ---------------------------------------------------------------------- Seenkao · 2022-04-12 17:47 MarkMLl, неоптимизированный кусок кода для одного вызова 10 байт (всего вызовов 50 - итого (500 - 3) байт - из-за нуля): eng: MarkMLl, unoptimized piece of code for one call 10 bytes (total calls 50 - total (500 - 3) bytes - due to zero): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i project1.lpr:79                           ADD(_one);00000000004010A6 bf01000000               mov    $0x1,%edi00000000004010AB e8e0ffffff             callq  0x401090 код в цикле не тянет на 500 байт: eng: the code in the loop does not pull 500 bytes: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i project1.lpr:134                          for n := 0 to 49 do00000000004010A6 c705500d0300ffffffff     movl   $0xffffffff,0x30d50(%rip)        # 0x431e00 00000000004010B0 8b054a0d0300             mov    0x30d4a(%rip),%eax        # 0x431e00 00000000004010B6 83c001                   add    $0x1,%eax00000000004010B9 8905410d0300             mov    %eax,0x30d41(%rip)        # 0x431e00 project1.lpr:135                          ADD(mass[n]);00000000004010BF 89c2                     mov    %eax,%edx00000000004010C1 488d0578700200           lea    0x27078(%rip),%rax        # 0x428140 00000000004010C8 0fb63c10                 movzbl (%rax,%rdx,1),%edi00000000004010CC e8bfffffff               callq  0x401090 project1.lpr:134                          for n := 0 to 49 do00000000004010D1 833d280d030031           cmpl   $0x31,0x30d28(%rip)        # 0x431e00 00000000004010D8 7cd6                     jl     0x4010b0   Пожалуйста, не держите меня за новичка! Проблема в инициализации массива. Если я вручную его буду заполнять, то размер программы так же будет меньше, чем в программе которую я приложил (обновляю выложенную программу, потому что в цикле допустил ошибку. Сделал цикл не на 50, а на 10, где цикл как раз раскрывается). На данный момент я хочу знать, как мне инициализировать массивы стандартным образом, но чтоб они инициализировались более-менее нормально. Я вполне понимаю, что я могу то же самое сделать через динамические массивы, но я не хотел бы этим заниматься (но видимо придётся). google translate: Please don't take me for a newbie! The problem is array initialization. If I manually fill it in, then the size of the program will also be smaller than in the program that I attached (I update the posted program, because I made a mistake in the cycle. I made the cycle not by 50, but by 10, where the cycle just opens). For now, I want to know how can I initialize arrays in a standard way, but so that they are initialized more or less normally. I fully understand that I can do the same thing through dynamic arrays, but I would not want to do this (but apparently I have to). ---------------------------------------------------------------------- speter · 2022-04-13 00:28 Quote from: Seenkao on April 12, 2022, 07:47:33 pm... I want to know how can I initialize arrays in a standard way, but so that they are initialized more or less normally... You should be able to use default() or fillchar() to initialise arrays!? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  tlist = array [0..20] of byte;var  it : tlist;begin  it := default(tlist);// or  fillchar(it,sizeof(it),0);end. cheers S. ---------------------------------------------------------------------- Joanna · 2022-04-13 06:34 I use constant arrays a lot but I haven’t worried about size at runtime yet. I wonder if it would help to use a packed array ?  Does that make it smaller ? ---------------------------------------------------------------------- Red_prig · 2022-04-13 07:57 testing on two versions of the compiler 3.3.1 (x86_64 linux) and 3.2.0 (x86_64 linux) revealed that the program with a static array is only 64 bytes more, which can be considered data alignment in memory, I don’t imagine how you got a big difference ---------------------------------------------------------------------- Seenkao · 2022-04-13 10:06 Quote from: Red_prig on April 13, 2022, 09:57:55 amtesting on two versions of the compiler 3.3.1 (x86_64 linux) and 3.2.0 (x86_64 linux) revealed that the program with a static array is only 64 bytes more, which can be considered data alignment in memory, I don’t imagine how you got a big difference Разница небольшая, но вы кажется не понимаете, что код, который повторяется несколько десятков раз, в любом случае будет больше массива из тех же десятков байт. Читайте что написано было ранее. 500 байт кода = 50 байт массива? И при этом программа с массивом получается больше размером? Вы уверены в том, что вы пишите? google translate: The difference is small, but you don't seem to understand that a code that is repeated dozens of times will in any case be larger than an array of the same dozens of bytes. Read what was written earlier. 500 bytes of code = 50 bytes of array? And thus the program with an array turns out more in the size? Are you sure what you are writing? Я проверил дальше и сделал массив из 100 элементов. И теперь с большой уверенностью могу сказать, что это баг. Когда мы используем в массиве 100 элементов, программа выходит меньше размером. Изменение размера начинается в районе 90 элементов. Исходник прикладываю. google translate: I checked further and made an array with 100 elements. And now with great confidence I can say that this is a bug. When we use 100 elements in an array, the program is smaller. Resizing starts at about 90 elements. I am attaching the source. ---------------------------------------------------------------------- Red_prig · 2022-04-13 10:48 Please do not mix the size of the executable code and the final size of the program file in one claim. The final size of the program is affected by more factors than the same size of the code, for example, in the case of a static array, an additional section is likely to be allocated for it, and taking into account the alignment and other requirements of the executable file structure, as a result, the final size of the program may become larger than its dynamic version. If you really want to dive into this so much, then consider it all at the level of "Executable and linking format". ---------------------------------------------------------------------- PascalDragon · 2022-04-13 10:54 Quote from: Seenkao on April 13, 2022, 12:06:50 pmI checked further and made an array with 100 elements. And now with great confidence I can say that this is a bug. When we use 100 elements in an array, the program is smaller. Resizing starts at about 90 elements. I am attaching the source. I can not reproduce your claims with your example code (x86_64-linux, FPC 3.2.0, compiled with -O3 -CX -XX): Code: [Select][sven@Tayet git]$ ls -l testoutput/sizetest* -rwxrwxrwx 1 sven users 34864 Apr 13 12:44 testoutput/sizetest1-linux // 50 elements, no TEST_OPTIMIZED -rwxrwxrwx 1 sven users 34928 Apr 13 12:43 testoutput/sizetest2-linux // 50 elements, TEST_OPTIMIZED -rwxrwxrwx 1 sven users 34864 Apr 13 12:45 testoutput/sizetest3-linux // 100 elements, no TEST_OPTIMIZED -rwxrwxrwx 1 sven users 34976 Apr 13 12:45 testoutput/sizetest4-linux // 100 elements, TEST_OPTIMIZED The size increase of the 50 elements case is 64 Byte and of the 100 elements case is 112, the missing difference probably due to size alignment inside the raw sections of the ELF file. ---------------------------------------------------------------------- BobDog · 2022-04-13 11:16 Quote from: speter on April 13, 2022, 02:28:29 amQuote from: Seenkao on April 12, 2022, 07:47:33 pm... I want to know how can I initialize arrays in a standard way, but so that they are initialized more or less normally... You should be able to use default() or fillchar() to initialise arrays!? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  tlist = array [0..20] of byte;var  it : tlist;begin  it := default(tlist);// or  fillchar(it,sizeof(it),0);end. cheers S. I use speter's code above with 20000 elements, and the fillchar option. Geany compile size.bas to size.exe = 123 kb. Then strip size.exe =44kb. So that is my humble input to this thread, strip it if you have it (strip.exe) ---------------------------------------------------------------------- Seenkao · 2022-04-13 21:00 Quote from: PascalDragon on April 13, 2022, 12:54:46 pmI can not reproduce your claims with your example code (x86_64-linux, FPC 3.2.0, compiled with -O3 -CX -XX): Code: [Select][sven@Tayet git]$ ls -l testoutput/sizetest* -rwxrwxrwx 1 sven users 34864 Apr 13 12:44 testoutput/sizetest1-linux // 50 elements, no TEST_OPTIMIZED -rwxrwxrwx 1 sven users 34928 Apr 13 12:43 testoutput/sizetest2-linux // 50 elements, TEST_OPTIMIZED -rwxrwxrwx 1 sven users 34864 Apr 13 12:45 testoutput/sizetest3-linux // 100 elements, no TEST_OPTIMIZED -rwxrwxrwx 1 sven users 34976 Apr 13 12:45 testoutput/sizetest4-linux // 100 elements, TEST_OPTIMIZED The size increase of the 50 elements case is 64 Byte and of the 100 elements case is 112, the missing difference probably due to size alignment inside the raw sections of the ELF file. Благодарю! Я хотел узнать, вы компилировали в системе Linux или Windows - кросс- компилятором? При включенной оптимизации у меня размер программы 31 488 байт. На 100 элементов. Остальные данные такие же как у вас. Google translate: Thanks to! I wanted to know if you compiled on a linux or windows system - cross compiler? With optimization enabled, my program size is 31,488 bytes. For 100 items. The rest of the information is the same as yours. Quote from: Red_prig on April 13, 2022, 12:48:13 pmPlease do not mix the size of the executable code and the final size of the program file in one claim. The final size of the program is affected by more factors than the same size of the code, for example, in the case of a static array, an additional section is likely to be allocated for it, and taking into account the alignment and other requirements of the executable file structure, as a result, the final size of the program may become larger than its dynamic version. If you really want to dive into this so much, then consider it all at the level of "Executable and linking format". Когда вы отвечаете в подобном формате, я думаю стоит посмотреть программу. И знать ассемблер. В данной программе менялось только то, что в одном варианте есть массив, а в другом нет. Если вы можете конкретно сказать в чём проблема, то я с радостью вас выслушаю! google translate: When you answer in this format, I think it's worth watching the program. And know assembler. In this program, the only thing that has changed is that in one version there is an array, and in the other there is not. If you can specifically tell what the problem is, then I will gladly listen to you! Было бы хорошо, если бы был человек, который мог "показать" процесс компилятора FPC. Либо указать, где можно взглянуть, чтобы понять этот процесс. Eng: It would be nice if there was a person who could "show" the process of the FPC compiler. Or indicate where you can look to understand this process. ---------------------------------------------------------------------- Red_prig · 2022-04-14 09:19 QuoteWhen you answer in this format, I think it's worth watching the program. And know assembler. In this program, the only thing that has changed is that in one version there is an array, and in the other there is not. If you can specifically tell what the problem is, then I will gladly listen to you! Your question already contains the answer, in one case there is a static array, in the other case not. I would even say this: a static array is directly transferred to the final program file. In the case of the dynamic version, additional assembler code is created that initializes the dynamic data. Therefore, the comparison of different initialization methods is not correct. And yes, for a better understanding, you need to go deeper. ---------------------------------------------------------------------- PascalDragon · 2022-04-14 09:53 Quote from: Seenkao on April 13, 2022, 11:00:55 pmThanks to! I wanted to know if you compiled on a linux or windows system - cross compiler? With optimization enabled, my program size is 31,488 bytes. For 100 items. The rest of the information is the same as yours. I've done it in WSL, so it's a native Linux compiler, but on a Windows system... Would you please provide the output of ld --version, maybe that will give a hint... Quote from: Seenkao on April 13, 2022, 11:00:55 pmEng: It would be nice if there was a person who could "show" the process of the FPC compiler. Or indicate where you can look to understand this process. If an internal assembler is used (which is the default on x86_64 Linux and Windows) the compiler directly generates the object files. If an external assembler is used (which can be triggered by specifying -al for example) the compiler writes the assembly source files and then calls the assembler for each to get the object files. Afterwards it calls the linker (in case an external linker is used as is the case on Linux by default) which will generate the final executable. It's then the task of the linker to pad any sections that are not up to its section alignment (the compiler can provide alignment requirements for single sections, but in normal cases it won't). For example on Windows the alignment of sections by default is 512 Byte. So if a section has a size that is not a multiple of that, the linker will blow it up to the next multiple. In extreme cases this could mean that only a single Byte of the final 512 Byte block of a section is occuppied which would lead to a “waste” of 511 Byte. ELF probably has something similar though I'm not as firm in ELF as I am in PE/COFF. ---------------------------------------------------------------------- Seenkao · 2022-04-14 11:21 Quote from: Red_prig on April 14, 2022, 11:19:58 amYour question already contains the answer, in one case there is a static array, in the other case not. I would even say this: a static array is directly transferred to the final program file. In the case of the dynamic version, additional assembler code is created that initializes the dynamic data. Therefore, the comparison of different initialization methods is not correct. And yes, for a better understanding, you need to go deeper. Я уже писал, что это инициализация массивов. Как производит инициализацию массива компилятор, мне не известно. А писать собственные алгоритмы на каждый такой случай - не лучший вариант. Я могу просто выделить память и загрузить туда данные. И пользоваться данным участком памяти как массивом. Но меня интересует не только мой вариант. А чтоб подобное не происходило, когда человек будет создавать свои программы, и объявляя небольшие массивы постоянно терял в размере программы. Я знаю, что я ерундой страдаю в нынешних реалиях. Но я так же знаю, что именно небольших массивов больше объявляют, чем больших. И в больших программах это выльется большими потерями данных. google translate: I already wrote that this is the initialization of arrays. I don't know how the compiler initializes the array. And writing your own algorithms for each such case is not the best option. I can just allocate memory and load data into it. And use this memory area as an array. But I'm not only interested in my version. And so that this does not happen when a person creates his programs, and declaring small arrays, he constantly loses in the size of the program. I know that I suffer from nonsense in the current realities. But I also know that it is precisely small arrays that are declared more than large ones. And in large programs, this will result in large data losses. Quote from: PascalDragon on April 14, 2022, 11:53:50 amWould you please provide the output of ld --version, maybe that will give a hint... GNU ld(GNU Binutils for Debian) 2.31.1 Copyright (C) 2018 Free Software Foundation, Inc. Возможно дело не в этом. У меня стоят разные компиляторы и на ноутбуке стоит FPC 3.2.1-r49243 и FPC 3.2.2-r49371. Я установил FPC 3.2.0 и там уменьшение кода работает только при 100 элементах, а не при 90, как в ранее установленных компиляторах. Но всё равно работает у меня. Люди проверяли на 3.0.4 и говорили что оптимизации нет. Я не проверял. google translate: Maybe that's not the point. I have different compilers and my laptop has FPC 3.2.1-r49243 and FPC 3.2.2-r49371. I installed FPC 3.2.0 and there code reduction only works at 100 elements, and not at 90, as in previously installed compilers. But it still works for me. People checked on 3.0.4 and said that there is no optimization. I didn't check. ---------------------------------------------------------------------- Red_prig · 2022-04-14 14:12 QuoteI already wrote that this is the initialization of arrays. I don't know how the compiler initializes the array. And writing your own algorithms for each such case is not the best option. I can just allocate memory and load data into it. And use this memory area as an array. But I'm not only interested in my version. And so that this does not happen when a person creates his programs, and declaring small arrays, he constantly loses in the size of the program. I know that I suffer from nonsense in the current realities. But I also know that it is precisely small arrays that are declared more than large ones. And in large programs, this will result in large data losses. If there are a bunch of small static arrays, the compiler will probably collect them into one contiguous heap, so I think that even in this case the loss will always be constant within a few tens of bytes. (Not per array but per program I mean) You can test it if you are interested. ---------------------------------------------------------------------- Seenkao · 2022-04-14 16:56 Quote from: Red_prig on April 14, 2022, 04:12:00 pmIf there are a bunch of small static arrays, the compiler will probably collect them into one contiguous heap, so I think that even in this case the loss will always be constant within a few tens of bytes. (Not per array but per program I mean) You can test it if you are interested. Благодарю! Вы помогли мне. Я создал два дополнительных модуля и добавил в каждый модуль по новом массиву. Уменьшил массивы до 30-50 элементов и получил оптимизацию. Значит вы правы и компилятор собирает данные. А значит оптимизация не работает только для маленьких программ? Где используются небольшие массивы. Я буду проверять, и в случае надобности подниму тему. Google translate: Thanks to! You helped me.I created two additional modules and added a new array to each module. Reduced arrays to 30-50 elements and got optimization. Means you are right and the compiler collects the data. Does this mean that optimization does not work only for small programs? Where small arrays are used. I will check, and if necessary, I will raise the topic. ---------------------------------------------------------------------- PascalDragon · 2022-04-18 11:18 Quote from: Seenkao on April 14, 2022, 01:21:54 pmI already wrote that this is the initialization of arrays. I don't know how the compiler initializes the array. And writing your own algorithms for each such case is not the best option. I can just allocate memory and load data into it. And use this memory area as an array. The compiler doesn't initialize the arrays at runtime, it emits the code into a .data or .rodata section that is then part of the binary and the variables or constants will simply point to the corresponding area inside these sections. Quote from: Seenkao on April 14, 2022, 01:21:54 pmBut I'm not only interested in my version. And so that this does not happen when a person creates his programs, and declaring small arrays, he constantly loses in the size of the program. As already hinted at in other replies: ELF and PE/COFF files have certain alignments, so adding a few Byte as data might result in a larger increase of the binary size (e.g. on Windows it will be a multiple of 512 Byte by default). I personally wouldn't bother with a few Byte here or there (except if you're working on something for microcontrollers where every Byte counts) cause more often than not the final code will be much larger than the data anyway. Quote from: Red_prig on April 14, 2022, 04:12:00 pmQuoteI already wrote that this is the initialization of arrays. I don't know how the compiler initializes the array. And writing your own algorithms for each such case is not the best option. I can just allocate memory and load data into it. And use this memory area as an array. But I'm not only interested in my version. And so that this does not happen when a person creates his programs, and declaring small arrays, he constantly loses in the size of the program. I know that I suffer from nonsense in the current realities. But I also know that it is precisely small arrays that are declared more than large ones. And in large programs, this will result in large data losses. If there are a bunch of small static arrays, the compiler will probably collect them into one contiguous heap, so I think that even in this case the loss will always be constant within a few tens of bytes. (Not per array but per program I mean) You can test it if you are interested. Static data is not part of the heap, but part of the executable and is then mapped as is into the virtual memory of the process. ---------------------------------------------------------------------- Red_prig · 2022-04-18 11:51 Quote from: PascalDragon on April 18, 2022, 01:18:48 pm Static data is not part of the heap, but part of the executable and is then mapped as is into the virtual memory of the process. by heap, I meant that they are packed with an unknown sequence between ---------------------------------------------------------------------- Seenkao · 2022-04-21 06:14 PascalDragon, меня больше беспокоило, что это может вызвать бесконтрольное увеличение программы на каждый создаваемый массив. Иногда я делаю поспешные выводы. Основанные на малых программах. Благодарю за информацию!  google translate: PascalDragon, I was more worried that this might cause the program to grow uncontrollably for every array it creates. Sometimes I jump to conclusions. Based on small programs. Thank you for the information! ---------------------------------------------------------------------- PascalDragon · 2022-04-21 12:31 Quote from: Seenkao on April 21, 2022, 08:14:47 amPascalDragon, I was more worried that this might cause the program to grow uncontrollably for every array it creates. Sometimes I jump to conclusions. Based on small programs. Thank you for the information! No, that shouldn't be the case. It should grow roughly in the magnitude of the size of the array (though, as said, alignment might mess this up).