Home » C# Programming

Vector vs. Array speed


I have a program that originally used c-style arrays, now I changed most of the arrays to use vectors, the problem is that the performance worsened by 60%.

Here are the steps in the code

1. Resize arrays based on input

2. Start Timer - to calculate time to run program

3. Do Calculations using vectors

4. End Timer


There was no resizing of the vectors, it just seems that if you are doing a lot of calculation on vectors they are slower then arrays by about 60%.  This seemed kind of high, does this make sense?

If vectors are this much slower I might try new/delete instead despite the drawbacks.





6 Answers Found


Answer 1

Did you test in Release mode? Did you turn off checked iterators by setting _SECURE_SCL and _SECUIRE_SCL_THROWS to 0?

Answer 2

Were your tests done with Debug builds or Release builds?

Were your tests done with checked iterators enabled or not?
(On by default.)

Checked Iterators

- Wayne

Answer 3



I just checked in "release" mode and the time  is the same.


I was worried for a moment.


Answer 4

I have tested the std::vector ad nauseum with various number theory projects. I have also used std::array and std::bitset and I can say this, std::vector, while imperfect gets the job done.

I built a wrapper around the std::vector to be able to do parallel things to it.

I went further into matrix formulas as well.

std:vector will give you reasonable performance.



Answer 5

What was the performance  drawback with the array.  I don't care about time  to resize  the  vector.  Arrays can't allocate deallocate memory and that seems like a huge drawback.

Answer 6

In my program, sieve.cpp I used char *, std::bitset, and std::vector as various containers and ran it.

It did not take long before the char* was dumped as its very profligate with memory. So I tried std::bitset, that choked at pow(2,32) so I was annoyed as usual.

So finally I tried std::vector<bool> which is the only construct available that can work with a cross off lise greater than pow(2,32)

So the sieve has the problem  of RAM consumption, using a single bit is as good as it gets.

Moving to parallel improved the performance  suggesting the CPU cache was helping.

The std::array is no better as its not as specialized as std::vector yet. I was also very disappointed over the limitations of the std::bitset which should have used size_t for its indexes.

Any programs offered on my site are 64-bit only. 32-bit need not apply.






My program used to use single dimensional variables to do some of the calculations, these were changed to vectors, in an updated version of the code.  But it slowed down alot, by about 100%.


Here is a snippet of the code.  Does this make sense, or is it more likely due to another culprit?  Thanks



Old Code:

void WB_QBenPmtProportional(void)
    double tBenPmt;
    tBenPmt = GmwbBenPayment[TT];
        if (tBenPmt>FundT) tBenPmt = FundT; //Cap payment at Fund Value
        Dec_WbPmt[TT] = 1 - tBenPmt/FundT;    //Used in DB Loop
        Fund1 = Fund1 - tBenPmt * Fund1/FundT;  
        Fund2 = Fund2 - tBenPmt * Fund2/FundT; 
        Fund3 = Fund3 - tBenPmt * Fund3/FundT; 
        Fund4 = Fund4 - tBenPmt * Fund4/FundT; 
        Fund5 = Fund5 - tBenPmt * Fund5/FundT; 
        Fund6 = Fund6 - tBenPmt * Fund6/FundT;
        FundT = FundT - tBenPmt;
        if(FundT<=0) Fund_FixNegativeAV();



New Code:

void WB_QBenPmtProportional_Test(void)
    double tBenPmt;
    tBenPmt = GmwbBenPayment[TT];
        if (tBenPmt>FundArray[0][TT]) tBenPmt = FundArray[0][TT]; //Cap payment at Fund Value
        Dec_WbPmt[TT] = 1 - tBenPmt/FundT;    //Used in DB Loop
        FundArray[1][TT] = FundArray[1][TT] - tBenPmt * FundArray[1][TT]/FundArray[0][TT];  
        FundArray[2][TT] = FundArray[2][TT] - tBenPmt * FundArray[2][TT]/FundArray[0][TT]; 
        FundArray[3][TT] = FundArray[3][TT] - tBenPmt * FundArray[3][TT]/FundArray[0][TT]; 
        FundArray[4][TT] = FundArray[4][TT] - tBenPmt * FundArray[4][TT]/FundArray[0][TT]; 
        FundArray[5][TT] = FundArray[5][TT] - tBenPmt * FundArray[5][TT]/FundArray[0][TT]; 
        FundArray[6][TT] = FundArray[6][TT] - tBenPmt * FundArray[6][TT]/FundArray[0][TT];
        FundArray[0][TT] = FundArray[0][TT] - tBenPmt;
        if(FundArray[0][TT]<=0) Fund_FixNegativeAV();


There are a bunch of functions, and I just changed Fund1 to FundArray[1][TT], where TT is the index.  I loop through TT = 1 to 360, for 1000 scenarios.


Would changing the functions from the single dimensional Fund1 to the array slow down the code from 250 seconds to 500 seconds.  Or is this unlikely.

Visual studio express, 2008



int d1[5] = {1, 3, 0, 4, 4};

vector d;

d = d1; // no handler to deal with the cast

so what do I need to do for my = operator to work n this case




I am encountering a problem when using a large array with two dimensions.

After destroying the array I will get a heap fragmentation.

I have written a little unmanaged C++ console application (VS 2008) to demonstate the problem.

The operating system is Windows XP SP3.

Here is an example to reproduce the problem:


int _tmain(int argc, _TCHAR* argv[])
    AllocateAndFree_1GByte_OneDimension(); // OK

    AllocateAndFree_1GByte_TwoDimension(); // OK, but single memory blocks will stay "Commited" in heap and the rest will stay "Reserved"

    AllocateAndFree_1GByte_OneDimension(); // error "Out of memory"

    return 0;

void AllocateAndFree_1GByte_OneDimension()
    BYTE* pTest = new BYTE[1024*1024*1024]; // allocate 1 GByte
    delete [] pTest;

void AllocateAndFree_1GByte_TwoDimension()
    int iOuterSize = 1024*1024;
    int iInnerSize = 1024;

    BYTE** apData = new BYTE*[iOuterSize];

    for (int iIndex = 0; iIndex < iOuterSize; ++iIndex)
        apData[iIndex] = new BYTE[iInnerSize];

    for (int iIndex = 0; iIndex < iOuterSize; ++iIndex)
        delete [] apData[iIndex];

    delete [] apData;


I got the same problem if I am using a STL vector:


I have analyzed the virtual address space of the process using the tool VMMap.exe.

I have seen that there persists several single 4k pages as "Committed" after destroying the two dimensional array. The rest of the 1 GByte memory blocks will stay as "Reserved"!!!   

If I change the value for the "iOuterSize" and "iInnerSize" (iOuterSize = 1024 and iInnerSize = 1024*1024) all seems to be OK.


What's wrong?


I am running the 64-bit version of Windows 7 Enterprise on an MacBook Pro.  What is the reason the following code crashes when built and run using Visual C++ 2008 Express?


#include <vector>
using std::vector; namespace { struct Data { int value; vector<int> extra; }; } int main() { const size_t COUNT = 10; vector<Data> source(COUNT); unsigned char buffer[COUNT * sizeof(Data)]; Data* target = reinterpret_cast<Data*>(buffer); std::copy(source.begin(), source.end(), target); return 0; }


This program run fine when built with the GNU compiler.




I am resizing a 2 dimensional vector.  It works for most of the arrays but for some reason at this point in the code it is not resizing to the correct number of indexes.  I want 7561, and it resizes to 766.

1. int xx = Duration *30+1; //Duration = 252

TimeTicksAnn.resize(5,vector<double>(xx)); //doesnt resize

TimeTicksAnn.resize(5,vector<double>(7561)); //still doesnt resize

I notice that if I resize at the begining of the code

Main{TimeTicksAnn.resize(5,vector<double>(xx)); } //works

Function2{TimeTicksAnn.resize(5,vector<double>(xx)); } //doesnt resize after.

the second call I make to resize is not working.

It was resized in the code earlier, does that make a difference, I can't figure out why it isn't working.

Also does anyone know how to get the size of the 2d vector.

I use int a = TimeTicksAnn.size();, but this returns 5, how do you get the second indice?




I need to read some settings values from an input file, by means of an openfiledialog and assign these values to a dynamic data structure a vector for example.

Then I need to use these vectors, in another function. I want to read the comma separated  file per line and do a logical test to determine in which vector to put the content on that line.

The questions are:

1.How do I make these vectors globally available in C++;I'm doing the assignment of the vectors content in a button click event handler and I do the calculation that needs to use the vector in a different button click event handler.

This is the header for the function that needs to use the vectors:

void collissionProb3(vector<vector<double> >& multidimvec,int NMAT,int NCELL,double MESHSIZE[],int MATPAP[],double DELTA[],double XT[]);

This works fine if I initialize the vectors in the same event handler where I call collissionProb3, but I need to assign the vectors from a file, then call collissionProb3

2. How does string.split(stringName,separatingChar) work in C++: in VB you can do something like a=string.split(stringName,",")(0) to get the first element of the string before the separating comma in this example.


Thanks ,




I was wondering, in a function I am working on for my tensor library is called eigen decomposition.

So given a matrix * vector = vector -> R x N  N x 1  = R x 1

I have 2 classes, vector and matrix

I tried it in vector, disliked the matrix constructor I tried

matrix<T> is the way I tried, no good

I prefer to support it in a class if possible.



Elected! Your votes and support have got me my 2010 MVP!

Developer | Windows IT | Chess | Economics | Hardcore Games | Vegan Advocate | PC Reviews


I am little confused about imapiv2 speeds.

I have two test discs:

1 x BD-RE 2x 25GB

1 x BD-R 4x 25GB

The drive returns these same capable speeds for each of the discs.

if I set the write speed for the BD-RE as follows:

hr = SetWriteSpeed(4389, VARIANT_FALSE);

(The 4389 was the bps returned by imapiv2 as the fastest speed available)
The function returns S_OK and the final speed when burning is 2.0x speed
so all is fine and exactly as expected.

Using the same code, the BD-R returns its fastest speed as 8779 bps
so I set the write speed just like above as:

hr = SetWriteSpeed(8779, VARIANT_FALSE);

The function returns S_OK so all is fine.
However the write burns at an average rate of 0.7x speed. This totally confuses me, as
everything set seems to be fine, and the BD-RE can burn as expected, but the BD-R burns
at less than half of the speed the BD-RE manages.

Even using -1 for the bps for fastest speed available has no effect for BD-R,
result is still very slow.

I have also confirmed with get_CurrentWriteSpeed that the speed set is the current
and it is.
I cannot see anything I am doing wrong. Can anyone throw any light on this?




Does the use of update panels increase the speed of a website?

A code sample:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<asp:Panel ID="Panel1" runat="server" HorizontalAlign="Left" Wrap="False" ScrollBars="Vertical" style="position: relative">
<asp:Label ID="LabelClock" runat="server" Text="Label"></asp:Label>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>



<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">

<asp:Panel ID="Panel2" runat="server">
<asp:Label ID="LabelNumber" runat="server" Text="Label"></asp:Label>



LabelClock.Text is set at every postback in the page load event, to the current time. But the UpdatePanel1 is only updated when the contents (some text) of the Literal1 changes.

This works, the text of the LabelClock only changes when the contents of the Literal1 changes as well.

However, there is a marked speed difference between 'loading times' (a single number is loaded into the LabelNumber in UpdatePanel2) depending on how much text the Literal1 shows in UpdatePanel1. When the Literal1 contains a lot of text, the speed is slow, when it contains little text, it is faster. Even though UpdatePanel1 is not updated (as confirmed by the LabelClock).

It appears that the data contained in the UpdatePanel is downloaded to the client on every postback, even though the updatepanel is not updated.

Could this be true?

Why is that?

How can it be changed, so as to increase the speed of the website?

Thank you.

With best regards,



Hi guys my task to switch the positions of pixels to distort an image

i heard when you want to switch a pixel with pixel you have to switch the rgb colors thats why i thought need the rgb value of the pixel. is that the correct direction for me to work on?

for example i want to switch position A with position B i would need another variable such as position C so that when i switch from position A to position B my position A value wont be lost

such as A = 2
B = 3
C = unknown

i move C = A
A = B
B = C

is that the correct way? please advise. I know how to work out in theory but i am very poor with Visual Basic therefore need help with coding

 i need help with inserting Bitmap into array I have done that part but i do not know if that is correct

this will allow me extraction of pixel from the array and finally taking out the RGB Colors and swapping the RGB colors to switch the pixels position

Below is the codes that i am having so far










Class Form1


PublicFunction CopyDataToBitmap(ByVal data AsByte()) As Bitmap


'Here create the Bitmap to the know height, width and format


Dim bmp AsNew Bitmap(640, 480, PixelFormat.Format24bppRgb)


'Create a BitmapData and Lock all pixels to be written


Dim bmpData As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.[WriteOnly], bmp.PixelFormat)


'Copy the data from the byte array into BitmapData.Scan0

Marshal.Copy(data, 0, bmpData.Scan0, data.Length)



'Unlock the pixels




'Return the bitmap


Return bmp




Dim I1 As Bitmap


Dim Cx, Cy, TF, mp, o(256), grn(256), blue(256), red(256) AsInteger


Dim I4 As Bitmap


Dim a AsInteger = 0


Dim check AsBoolean = False


'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Dim I3 As Bitmap = New Bitmap(I1.Width, I1.Height)


'Dim I4 As Bitmap = New Bitmap(I1.Width, I1.Height)


'End Sub


PrivateFunction CropBitmap(ByRef bmp As Bitmap, ByVal cropX AsInteger, ByVal cropY AsInteger, ByVal cropWidth AsInteger, ByVal cropHeight AsInteger) As Bitmap


Dim rect AsNew Rectangle(cropX, cropY, cropWidth, cropHeight)


Dim cropped As Bitmap = bmp.Clone(rect, bmp.PixelFormat)


Return cropped




PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Dim ReadingFileDialog AsNew OpenFileDialog


Dim fileOpened AsBoolean = False


If fileOpened = TrueThen


fileOpened =




ReadingFileDialog.Title =

"Open My File"


' Restrict our choice of files to *.jpeg files.

ReadingFileDialog.Filter =

"Bitmap *.bmp|*.bmp|JPEG *.jpg|*.jpg|GIF *.gif|*.gif"


If ReadingFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then



fileOpened =



Dim IPB As Bitmap = New Bitmap(ReadingFileDialog.FileName)


If ReadingFileDialog.FileName <> ""Then

PictureBox1.Image =

New Bitmap(ReadingFileDialog.FileName)





I1 = PictureBox1.Image




PrivateSub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


Dim Cx, Cy, o(256), grn(256), blue(256), red(256) AsInteger


Dim o1(256), r1(256), b1(256), g1(256) AsInteger'For histogram & rect draw box


Dim PHX(1240)


Dim DFR(1280, 1024), DFG(1280, 1024), DFB(1280, 1024), PHV(1600, 1200), HCX(1024) AsString


Dim DFRT(1280, 1024), DFGT(1280, 1024), DFBT(1280, 1024) AsInteger'### added temp color channels


Dim CT As Color ' color object


Dim wow AsBoolean = False


'Dim LMP As Point = MousePosition


Dim I3 As Bitmap


'= New Bitmap(I1.Width, I1.Height)`


' PictureBox1.Image = CropBitmap(I4, PictureBox1.Left, PictureBox1.Top, I4.Width / 2, I4.Height / 2)


'Code for getting percentage of comparing Cy,Cx to I1


' For Cx = 0 To I1.Width - 1


'For Cy = 0 To I1.Height - 1


'I1 = PictureBox1.Image


'CT = I1.GetPixel(20, 20) 'get the pixel data from the bitmap pixel


'PB2.Text = CInt(((Cy + 1) / I1.Height) * 100) & "%"


'DFR(20, 20) = CT.R 'DFR() is string (8-bit)


'PB2.Text = I1.Width


'DFG(Cx, Cy) = CT.G


'PB1.Text = DFG(Cx, Cy)


'DFB(Cx, Cy) = I1.Height


'PB1.Text = DFB(Cx, Cy)


'PB1.Text = (((CInt(Cx) + 1) / I1.Width) * 100) & "%"






'I3(0, 0) = I4


' I3(0, 1) = New Bitmap(I4.Width, I4.Height, 400, Drawing.Imaging.PixelFormat.Format24bppRgb, DFR(20, 20))


'PictureBox1.Image = I3(0, 0)


'PictureBox1.Height = I3(0, 0).Height


'PictureBox1.Width = I3(0, 0).Width


' Dim x, y As Integer


' 'Get color of the pixel


' For x = 1 To I1.Height


'For y = 1 To I1.Width


'Dim B(x, y) As Color


'A(x, y) = CT.R


'B(x, y) = CT


'B(x + 1, y + 1) = B(x, y)












PrivateSub Form1_Load(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMe.Load





PrivateSub Timer1_Tick_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick


Dim d AsNew Drawing.Bitmap(1, 1)


Dim b As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(d)



New Drawing.Point(MousePosition.X, MousePosition.Y), New Drawing.Point(0, 0), d.Size)


Dim c As Drawing.Color = d.GetPixel(0, 0)

PictureBox1.BackColor = c

PB2.Text = PictureBox1.BackColor.Name




PrivateSub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click





PublicSub GetPixel_Example(ByVal e As PaintEventArgs)


' Create a Bitmap object from an image file.


Dim myBitmap AsNew Bitmap("Grapes.jpg")


' Get the color of a pixel within myBitmap.


Dim pixelColor As Color = myBitmap.GetPixel(50, 50)


' Fill a rectangle with pixelColor.


Dim pixelBrush AsNew SolidBrush(pixelColor)

e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100)









a c# class's single dimension byte array contains socket level instrument sensor data as per:

publicstaticbyte[] frameData

whose indexed byte values need to be transferred into a single dimensional integer array which will be the basis for a vb.net graphics control to display the data as per;

Property Int_Clutter_In() AsInteger() 

How would I make this conversion, a byte array copy? (hmm, deep or shallow?)

Thank you!




I want to write an extension method that works with all kinds of arrays (Integer, String, Decimal, ...). It returns an array of the same type and size as the input parameter array.

The following code works:

    <Extension()> _
    Function DoSomething(ByVal arrIn As System.ArrayAs System.Array
        Dim arrOut = arrIn.Clone
        '...processing steps
        Return arrOut
    End Function

However in order to avoid the 2n operations (Clone, Clear) for very large arrays, I tried and failed with the following two attempts:

   <Extension()> _
    Function DoSomethingElse(ByVal arrIn As System.ArrayAs System.Array
        Dim arrOut() As Object 'how do I get the type of the input array?
        ReDim arrOut(arrIn.Length - 1)
        Return arrOut               'doesn't have the same type as input array
    End Function
  <Extension()> _
    Sub DoSomethingElse(ByVal arrIn As System.ArrayByRef arrOut As System.Array)
        ReDim arrOut(arrIn.Length - 1)  'error: Redim requires an arry ?!
        '...processing steps
    End Sub

What is the simplest and fastest way to say "create an empty array of same type and size as the input array" ?

thanks herbert



I am struggling with the function definition which takes arrays from two pointers?Please see the attached code.

Many thanks in advance for help!

/*This program lets the user enter two arrays of ten elements. It then displays the sum of values of two arrays into the third arrays*/
#include <stdio.h>
int x,y, array1[10],array2[10],*ptr1,*ptr2, call;
int sum( int *ptr1, int a, int *ptr2, int b);
int main()
	printf("Enter the 10 elements:\n");
	for (x=0;x<10;x++)

	printf("Enter the second 10 elements:\n");
	for (y=0;y<10;y++)
	printf("the first_array array1 you entered is\n");
	for (x=0;x<10;x++)
	printf("the second_array array2 you entered is\n");
	for (y=0;y<10;y++)
	printf("The added_array is %d",call);
	return 0;

int sum( int *ptr1, int a, int *ptr2, int b)
	int added_array[10];
	return added_array[10];


Hi there. I have a function, callable from C# in an interface looks something like this

 Process( float
[][] data ); 

It is implemented as follows in C++/CLI

void Process( array <array <float >^>^ data ) {
// create array of native pointers for interop
float ** ppData = newfloat *[data->Length];
for ( int i = 0; i < data->Length; ++i ) {
pin_ptr<float > pRow = &data[i][0]
ppData[i] = (float *) pRow
// call native function to process data in-place Native::Process( ppData );
// release memorydelete [] ppData;

However, although this will compile, I am not guaranteed that the GC will not move the managed arrays since the pin_ptr goes out of scope before Native::Process() is called. Since I can't create an array of pin_ptrs, how about

// pin the array
GCHandle ^hData = GCHandle::Alloc( data, GCHandleType::Pinned );
Native::Process( ppData );<br/>

Is this sufficient to pin the entire array, or could the GC still move the constituent data? Is it then necessary to do


<GCHandle^>^ hData = gcnewarray
for ( int i = 0; i < hData->Length; ++i ) {
hData[i] = GCHandle::Alloc( data[i], GCHandleType::Pinned );
Native::Process( ppData );
for ( int i = 0; i < hData->Length; ++i ) {


My intuition leads me to believe it's this second option, but a definitive answer would be great.






Im looking to implement a array containing a array of bool values.  I tryed to use

bool[,][,] CopyArray = newbool[8,8][8,8];
This produced the error "Error    1    Invalid rank specifier: expected ',' or ']' ".  Im not sure what to do about this,  Am i implementing the array wrong?

I have a web service that returns a large amount of data.  When the array size is about 4,000 the web service returns the data just fine.  Bump that up to over 7,000 and the web service just returns an empty array.  Any ideas on what I can change to get it to return all objects?


I need to convert char array to clr::array<char> say,

char a[10] ="hello";

array<char>^ charArray= gcnew array<char>(10);

charArray = a;//somthing like this

Is there any way to make this happen. Please help..... 


                   while converting arraylist to byte array ..it shows an exception called invalid cast exception ..how can i overcome it.and convert arraylist to byte array....in C#..


I'm sure this has been asked more then once, sorry for asking once again.. :(

Visual C++

I have a array<System::Byte> and a array<System::UInt32>..

Is there an easy way to convert a Byte array to a UInt32?

Please understand that I'm not looking for a one to one conversion.... In other words, I don't want each Byte converted into a UInt32..  The Byte array is a multiple of 4 Bytes. So the first 4 Bytes would make the first UInt32..

I'm working with Sockets and some of the data in the returned Byte array is an list of UInt32 values. It would be nice to have a built in .NET method to make pulling this out easier that how I'm doing it now.


I've been scratching my head a bit and am hoping someone could help me split an array up into multiple arrays. 


Say Class1 has a property GroupID and Class2 has a property called ID. 


Class1[] class1;

Class2[] class2;


I need to group all of the elements by GroupID and create a new array for each GroupID found in class1 and pass the GroupID of each element of class1 to the ID property of class2. 


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure