[英]What is the difference between the time complexities of vector <int> a {N, 0} and int arr a[N] = {0}
What is the difference between the time complexities of vector <int> a {N, 0}
and int arr a[N] = {0}
, when initializing them with a fixed variable?使用固定变量初始化vector <int> a {N, 0}
和int arr a[N] = {0}
的时间复杂度之间有什么区别?
If they both are same then what techniques can we use to decrease time complexity in our program when initializing arrays?如果它们都相同,那么在初始化数组时,我们可以使用哪些技术来降低程序的时间复杂度?
The vector data is allocated on the heap and the array on the stack.向量数据分配在堆上,数组分配在堆栈上。 Other than that hopefully you compiler will optimise both to a single memset(0)
.除此之外,希望您的编译器将两者都优化为单个memset(0)
。
To know the exact timing you will need to benchmark this yourself on your compiler.要知道确切的时间,您需要自己在编译器上对此进行基准测试。 I doubt that this will take a significant amount of time though, the rest of your program is likely to be slower.我怀疑这是否会花费大量时间,但程序的其余部分可能会更慢。
Write your program first, see if its fast enough.先写你的程序,看看它是否足够快。 If it isn't then profile it and concentrate on the slow bits.如果不是,则对其进行分析并专注于慢速位。 Making small optimisations like this before you even know whether they are needed is often fruitless.在您甚至不知道是否需要之前进行这样的小优化通常是徒劳的。
Vector allocates memory in the heap hence it is little expensive to allocate memory for vector since heap data structure need to search for available block of memory in heap. Vector 在堆中分配内存,因此为 vector 分配内存的开销很小,因为堆数据结构需要在堆中搜索可用的内存块。 In case of array, memory is allocated in stack which is equivalent reducing stack pointer.在数组的情况下,内存分配在堆栈中,相当于减少堆栈指针。 However both vector and array initializing almost takes same time, since both of the use memset
and then mapped to stos hardware instruction.然而,向量和数组的初始化几乎都需要相同的时间,因为两者都使用memset
然后映射到stos硬件指令。 Main difference is in allocating memory.主要区别在于分配内存。 When I was developing a high performance software, I did find that allocating and initializing vector was taking significant time (depends on the size).在开发高性能软件时,我确实发现分配和初始化向量需要花费大量时间(取决于大小)。
Time complexity of initialization is same for vector and array.向量和数组的初始化时间复杂度相同。 Allocating is vector far more expensive than vector.分配是向量远比向量昂贵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.